How to create a shallow Copy of a Set in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 28, 2021

banner

Photo from Unsplash

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 #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.