Hiprup

What happens with null and undefined in arithmetic?

They coerce to numbers differently in math.

  • null — becomes 0, so 5 + null is 5.

  • undefined — becomes NaN, so 5 + undefined is NaN.

Common bug: a missing property is undefined, which poisons calculations with NaN — default it first.

// null → 0 in arithmetic
console.log(null + 1);       // 1 (0 + 1)
console.log(null * 5);       // 0 (0 * 5)
console.log(null + null);    // 0 (0 + 0)

// undefined → NaN in arithmetic
console.log(undefined + 1);  // NaN
console.log(undefined * 5);  // NaN
console.log(undefined + undefined); // NaN

// Mixed
console.log(null + undefined); // NaN (0 + NaN)

// Equality
console.log(null == undefined);  // true (special rule)
console.log(null === undefined); // false (different types)
console.log(null == 0);          // false (null only == undefined)
console.log(null == '');         // false

null coerces to 0 (well-defined behavior). undefined coerces to NaN (any operation with NaN produces NaN). null == undefined is a special rule (both represent 'no value'). null does NOT == 0 or '' (only == undefined).

null → 0, undefined → NaN in arithmetic. null == undefined is true (special rule), null == 0 is false. NaN makes everything NaN.

These are common output prediction questions.

What happens with null and undefined in arithmetic? | Hiprup