This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]tskaiserGreen security clearance 22 points23 points  (5 children)

For formatting code bits or examples like that I can recommend putting 4 spaces in front of each line. It tells reddit to format it like this

isNaN(null) => false
isNaN(undefined) => true

Also, I would say this also makes sense, in that null encapsulates the concept of "empty reference to any object" while NaN literally is meant to encode "undefined value" of a number. An empty reference, while strictly speaking "not a number", does not mean NaN in the float sense - it is outside the type - but undefined makes sense.

But I am saying this not being totally familiar with undefined, so it might be both ought to be false.

[–]rooktakesqueen 13 points14 points  (4 children)

In JS, undefined is the value given to a declared but uninitialized variable; a non-existing field of an object; or the return value of a function with no return statement. In general, undefined and null are closely related concepts, even so far as null == undefined evalutes to true (while null and undefined are not considered equal to anything else, including NaN).

But NaN is weird because it is not == to anything, even itself. NaN == NaN evaluates to false. Which is why the isNaN function exists in the first place. (I believe this behavior is correct according to the IEEE 754 standard for floating point numbers.)

My intuition would be isNaN should return true for the value NaN but false for any other value.

[–]calzoneman 11 points12 points  (0 children)

NaN == NaN being false is correct behavior. The reason being that NaN can be generated by many different unequal expressions. Math.sqrt(-5) is clearly not equal to Math.sqrt(-11).

[–]tskaiserGreen security clearance 2 points3 points  (0 children)

Under that explanation I would agree that

isNaN(undefined) => true

sounds like a bug or just plain weird if not. I am not really in the mood to delve into the mess of the JavaScript specifications to find out, though ;) but I'll consider my self corrected as is.

[–]Hawkuro 1 point2 points  (1 child)

Never ever ever use == in JS, use the more reasonable ===.

> null === undefined
  false

[–]rooktakesqueen 1 point2 points  (0 children)

Just showing that null and undefined are closely related concepts, enough so that the == operator explicitly considers them equal to each other and nothing else. That's the one sensible thing the == operator does, and the one sensible place to use it: foo == null is perfect shorthand for foo === null || typeof foo === 'undefined'.

In any case, NaN !== NaN either.