Borislav Hadzhiev
Thu Oct 28 2021·1 min read
Photo by Kevin Lee
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
.
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
.
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
.
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'}