Sub topic 10
Edge Cases: NaN, -0, null, and undefined
This chapter assumes you already know how === and == work, what Object.is does, and how ToNumber converts values. It looks at the four values that break the usual rules. NaN is not equal to itself. -0 hides behind 0. null and undefined each follow their own conversion rules. You will learn where each one comes from, how each equality algorithm treats it, and how to test for it reliably.
NaN: the value that is not equal to itself
NaN ("Not a Number") is a value of type number. It represents a numeric result that has no meaningful value. It usually shows up silently, without throwing an error:
console.log(0 / 0); // NaN
console.log(Number('abc')); // NaN
console.log(Math.sqrt(-1)); // NaN
console.log(undefined + 1); // NaN
console.log(parseInt('px10')); // NaN
console.log(typeof NaN); // 'number'Once a NaN is created, it spreads through every arithmetic step that uses it. NaN * 0 is NaN, and Math.max(1, NaN) is NaN. A single bad input can turn a whole calculation into NaN.
The IEEE 754 floating-point standard says NaN compares unequal to everything, including itself. JavaScript follows that rule in ===, ==, and every relational operator:
const x = NaN;
console.log(x === x); // false
console.log(x == x); // false
console.log(x < 1); // false
console.log(x >= 1); // false
console.log(x !== x); // true: the only value for which this holdsTesting for NaN correctly
Because x === NaN is always false, you need a dedicated test. There are two global-looking functions, and they behave differently:
console.log(isNaN('abc')); // true: converts 'abc' to a number first
console.log(Number.isNaN('abc')); // false: 'abc' is a string, not NaN
console.log(isNaN(undefined)); // true
console.log(Number.isNaN(undefined)); // false
console.log(Number.isNaN(NaN)); // true
console.log(Object.is(NaN, 0 / 0)); // trueThe global isNaN runs ToNumber on its argument before checking, so it really answers the question "would this become NaN if converted?" Number.isNaN performs no conversion. It returns true only for the actual NaN value.
NaN in collections
Array and collection methods disagree about NaN because they use different equality algorithms. indexOf and lastIndexOf use strict equality. includes, Set, and Map use SameValueZero, which treats NaN as equal to itself.
const values = [1, NaN, 3];
console.log(values.indexOf(NaN)); // -1
console.log(values.includes(NaN)); // true
console.log(values.findIndex(Number.isNaN)); // 1
console.log(new Set([NaN, NaN]).size); // 1
const m = new Map([[NaN, 'found']]);
console.log(m.get(NaN)); // 'found'If you need the index of a NaN, use findIndex(Number.isNaN). indexOf can never find it.
-0: the zero you usually cannot see
JavaScript numbers follow IEEE 754, so they have both a positive and a negative zero. You get -0 from operations that keep the sign of a result that rounds or shrinks to zero:
console.log(-1 * 0); // -0
console.log(0 * -5); // -0
console.log(Math.round(-0.4)); // -0
console.log(-0 + 0); // 0
console.log(Math.min(0, -0)); // -0Most operations treat -0 as if it were 0. It is equal under === and ==, it is not less than 0, and it turns into '0' when converted to a string:
console.log(-0 === 0); // true
console.log(-0 < 0); // false
console.log(String(-0)); // '0'
console.log(`${-0}`); // '0'
console.log(JSON.stringify(-0)); // '0'The difference shows up when the sign matters. Dividing by zero gives an infinity with the zero's sign. Math.atan2 and Math.sign also preserve the sign:
console.log(1 / 0); // Infinity
console.log(1 / -0); // -Infinity
console.log(Object.is(Math.sign(-0), -0)); // true
console.log(Math.atan2(0, -0)); // 3.141592653589793
console.log(Math.atan2(0, 0)); // 0You can detect -0 with Object.is(x, -0). Older code uses x === 0 && 1 / x === -Infinity. In practice, -0 matters when a sign carries meaning. Examples include direction in animations or physics, a temperature that rounds to "-0°", and numeric code that divides by a value which may be zero.
null and undefined: two kinds of "nothing"
undefined means a value was never assigned. Examples are a missing argument, a missing property, or a declared variable with no value. null is an explicit "no value" that a programmer writes on purpose. In comparisons they follow three different sets of rules.
Under == they only equal each other
Loose equality has a special rule for these two values. null == undefined is true. Neither value is loosely equal to anything else, and no numeric conversion happens:
console.log(null == undefined); // true
console.log(null == 0); // false
console.log(undefined == 0); // false
console.log(null == false); // false
console.log(undefined == ''); // falseThis makes x == null a precise idiom for "x is null or undefined". It does not match 0, '', or false. Many style guides that otherwise ban == make an exception for this check.
Under relational operators they convert to numbers
Relational operators skip the special rule and apply ToNumber. null becomes 0 and undefined becomes NaN:
console.log(Number(null)); // 0
console.log(Number(undefined)); // NaN
console.log(null >= 0); // true
console.log(null <= 0); // true
console.log(null == 0); // false: the contradiction
console.log(undefined >= 0); // false
console.log(undefined <= 0); // false: NaN fails every comparisonThis is why null >= 0 and null <= 0 are both true while null == 0 is false. The two results come from different algorithms that happen to share similar-looking symbols.
In arithmetic the same split appears
console.log(null + 1); // 1
console.log(undefined + 1); // NaN
console.log(null * 5); // 0A missing property read as undefined turns arithmetic into NaN. A field set to null silently acts as 0. Both can hide bugs, but in different ways.
Comparison summary
| Pair | `===` | `==` | `Object.is` | SameValueZero (`includes`, `Set`) |
|---|---|---|---|---|
| `NaN`, `NaN` | false | false | true | true |
| `0`, `-0` | true | true | false | true |
| `null`, `undefined` | false | true | false | false |
| `null`, `0` | false | false | false | false |
Common mistakes
- Writing
if (x === NaN). This is always false. UseNumber.isNaN(x). - Using
indexOfto findNaNin an array. UseincludesorfindIndex(Number.isNaN). - Treating
null >= 0as evidence thatnullequals0. Relational operators and==use different rules. - Validating numeric input with the global
isNaN, which accepts non-numbers that only becomeNaNafter conversion. - Assuming
Object.isis a "better===" everywhere. Because it separates0from-0, it can make0and-0scores or prices look different.
Exercise
Predict each output: [NaN].indexOf(NaN), [0].includes(-0), Object.is(Math.round(-0.2), 0), null > -1, undefined == null.
Show answer
-1 (strict equality never matches NaN); true (SameValueZero treats 0 and -0 as equal); false (Math.round(-0.2) is -0, and Object.is separates -0 from 0); true (null converts to 0, and 0 > -1); true (the special == rule for null and undefined).
Exercise
A function receives price from a form. It must reject values that are missing, null, or that produce NaN, but it must accept 0. Write the check.
Show answer
function isValidPrice(price) { if (price == null) return false; const n = Number(price); return !Number.isNaN(n); } The price == null test catches null and undefined without rejecting 0. Number.isNaN on the converted value rejects input such as 'abc' and still accepts 0. Note that Number('') is 0, so you need an extra check if empty strings must also be rejected.
Exercise
Why is null <= 0 true while null == 0 is false?
Show answer
The <= operator converts null with ToNumber, which gives 0, so it evaluates 0 <= 0, which is true. The == operator has a dedicated rule: null is loosely equal only to null and undefined, so it never converts null to a number. The two operators use different algorithms.