0

After adding numbers to a JavaScript set, the set has (or contains) it:

let set = new Set();
set.add(1);
set.has(1);  // true

But after adding an array (or a set) to a set, it doesn't have (or contain) it:

set.add([0,1]);
set.has([0,1]);   //false

What am I doing wrong?

  • 1
    You'll probably need to pass in the same _exact_ array. Same reason `[0,1] === [0,1] // false` – evolutionxbox May 07 '21 at 10:02
  • 1
    Using `[0,1]` twice in your code creates two separate memory objects. Whether a set "has" a certain element is based on identity though, which means: are they the same object in memory? Which is not the case. – Chris G May 07 '21 at 10:03
  • @ChrisG: Might it be the case that Java sets behave differently? – Hans-Peter Stricker May 07 '21 at 10:04
  • 1
    That's very possible; the difference is that Java is compiled to bytecode while JS is interpreted. Afaik the compilation looks for identical literals in the source and uses a single object for all of them, so similar code will in fact behave differently with Java. (afaik) edit: oopsie, apparently no: https://ideone.com/iMeo9S It's true for Strings though: https://ideone.com/9ykwux – Chris G May 07 '21 at 10:05
  • @Hans-PeterStricker please always assume JavaScript works different to Java (even if they are similar and do work in similar ways). They are not the same language after all. – evolutionxbox May 07 '21 at 10:08
  • @Hans-PeterStricker In Java, objects can have an `.equals()` and `.hashCode()` methods in addition to `==`. The equality operator will compare objects by their reference. This is also how JS sets work. But Java sets use the `.hashCode()` method. IIRC few implementations also allow for custom comparison to be supplied to the set, instead of the one on the members. At any rate, the point is that the comparison is different. – VLAZ May 07 '21 at 10:15
  • Btw, the explanation for the difference (in Java) is that Arrays are mutable but Strings aren't. So using a single object for identical string literals is safe, while for arrays it wouldn't be at all. – Chris G May 07 '21 at 10:15

0 Answers0