DEV Community

Cover image for NaN and Set Keys
Nick Taylor
Nick Taylor

Posted on

NaN and Set Keys

On Thursday, during my JavaScriptHours stream, we came across something interesting.

In JavaScript, NaN !== NaN. With a Set, the values are unique. If you try to add the same value, there will always be one of it in the Set.

During the stream, I created a Set and added NaN to it twice. Some of the audience in the chat as well as myself were surprised and perplexed that the Set contained one value after adding NaN twice given that NaN !== NaN.

Does anyone know why this is? My only guess is that maybe there is a Symbol that indicates NaN is unique even though NaN !== NaN.

Top comments (4)

Collapse
 
link2twenty profile image
Andrew Bone

MDN states it as fact but doesn't give an actual reason.

NaN and undefined can also be stored in a Set. All NaN values are equated (i.e. NaN is considered the same as NaN, even though NaN !== NaN).

Collapse
 
nickytonline profile image
Nick Taylor • Edited

Thanks Andrew!

I guess I should read the docs, although that did not occur to me based on NaN !== NaN. 🙃

Like you mentioned, It’d be nice to have a more thorough explanation in the docs though.

Collapse
 
link2twenty profile image
Andrew Bone
Collapse
 
siddharthshyniben profile image
Siddharth • Edited

Maybe the Set uses Object.is() for comparison?

Object.is(NaN, NaN)