How to create a shallow Copy of a Set in JavaScript

avatar

Borislav Hadzhiev

Thu Oct 28 20211 min read

banner

Photo by Kevin Lee

Create a shallow Copy of a Set in JavaScript #

To create a shallow copy of a Set, pass the original Set as a parameter to the Set() constructor, e.g. const cloned = new Set(oldSet). The Set() constructor takes an iterable, such as another Set, and adds all of the elements to the new Set.

index.js
const set1 = new Set(['one', 'two', 'three']); const cloned = new Set(set1); console.log(cloned); // ๐Ÿ‘‰๏ธ {'one', 'two', 'three'}

We used the Set() constructor to create a shallow copy of a Set.

The only parameter the Set() constructor takes is an iterable, such as an array, string, or another Set.

Once the iterable is passed to the constructor, all of the unique values from the iterable are added to the new Set.

The new Set object has a completely different location in memory and adding elements to it would not add elements to the original Set.

index.js
const set1 = new Set(['one', 'two', 'three']); const cloned = new Set(set1); console.log(cloned); // ๐Ÿ‘‰๏ธ {'one', 'two', 'three'} cloned.add('four'); console.log(cloned); // ๐Ÿ‘‰๏ธ {'one', 'two', 'three', 'four'} console.log(set1); // ๐Ÿ‘‰๏ธ {'one', 'two', 'three'}

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee