1

Just spotted strange behavior of JS's Set object and decided to ask stackoverflow community :)
So that's the problem:

Screen from console:
enter image description here

Code for copy-paste:

let a = new Set([1])
let b = new Set([2, 3])
a.add(...b)  // result is set of {1, 2}


Problem is that set a does not contain value 3 after add function call. This behavior have an explanation or it's more like a bug?
Thanks in advance

dorintufar
  • 660
  • 9
  • 22

2 Answers2

3

You can add create a new set like this:

let a = new Set([1])
let b = new Set([2, 3])
const c = new Set([...a, ...b])

Variable c contains all the items that you need.

The problem is that the add method of the set get only one parameter, no a arguments, if for that reason that only add one value.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/add

Luis Louis
  • 644
  • 6
  • 21
0

If you do this:

let a = new Set([1])
a.add(2,3);

a will still only have 1,2 as elements. The spread operator is basically doing the same as above

TKoL
  • 13,158
  • 3
  • 39
  • 73