Null and Undefined Coercion Rules
You'll learn how null and undefined transform into different values depending on whether JavaScript needs a number, string, or boolean.
The Core Idea
Both null and undefined are special primitive values, but they behave differently when JavaScript coerces them to other types. Understanding these transformations helps you predict seemingly odd results in your code.
Numeric Context: Different Outcomes
When JavaScript needs a number:
nullbecomes0— it's treated as "zero" or "nothing numeric"undefinedbecomesNaN— it's treated as "not a valid number"
console.log(null + 5); // 0 + 5 = 5
console.log(undefined + 5); // NaN + 5 = NaN
console.log(null * 10); // 0 * 10 = 0
console.log(undefined * 10); // NaN * 10 = NaN
String Context: Literal Representations
When JavaScript needs a string, both convert to their literal text form:
nullbecomes"null"undefinedbecomes"undefined"
console.log("Value: " + null); // "Value: null"
console.log("Value: " + undefined); // "Value: undefined"
console.log(String(null)); // "null"
console.log(String(undefined)); // "undefined"
Boolean Context: Both Falsy
In boolean contexts (like conditionals), both are falsy values — they evaluate to false:
console.log(Boolean(null)); // false
console.log(Boolean(undefined)); // false
Why the Difference in Numeric Coercion?
Think of null as an intentional "empty value" — zero is a reasonable numeric representation. But undefined means "no value was ever set" — there's no sensible number for that, so JavaScript gives you NaN.
Key Takeaway: null coerces to 0 in numeric contexts while undefined becomes NaN; both become their string names when converted to strings and both are falsy in boolean contexts.