DEV Community

loading...
Cover image for NaN and Set Keys

NaN and Set Keys

Nick Taylor (he/him)
Lead software engineer at Forem. Caught the live coding bug on Twitch at livecoding.ca
・1 min read

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.

Discussion (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 (he/him) Author • 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)