How would you add an element to an existing Set when defining it? For example, if I have:
const s1 = Set([1,2,3]);
const elem = 4;
const s2 = s1 elem; // ?
Is using the spread operator (...) the correct way to do this?
s2 = new Set([...s, elem]);
Or is there another/better approach?
CodePudding user response:
Just use Set#add. Using const here only prevents setting s1 to another value, but does not make the Set immutable.
const s1 = new Set([1,2,3]);
const elem = 4;
s1.add(elem);
console.log([...s1]);
