Course contentsShow
← JavaScript
Lesson 292 of 2,7238. Type CoercionFree lesson

null and undefined in Arithmetic

Why null becomes 0 and undefined becomes NaN in numeric contexts, causing silent errors.

null and undefined in Arithmetic

You'll learn why null becomes 0 and undefined becomes NaN in math operations, and how this causes sneaky bugs.

The Silent Conversion

When JavaScript encounters null or undefined in arithmetic operations, it doesn't throw an error—it converts them to numbers using the ToNumber abstract operation you learned earlier:

  • null becomes 0: JavaScript treats "nothing" as zero in math
  • undefined becomes NaN: JavaScript treats "not yet defined" as "Not-a-Number"
console.log(5 + null);       // 6 (null → 0)
console.log(5 + undefined);  // NaN (undefined → NaN)

console.log(10 * null);      // 0 (null → 0)
console.log(10 * undefined); // NaN (undefined → NaN)

Why This Causes Silent Errors

The danger lies in how quiet these conversions are. If you accidentally use an undefined variable in a calculation, JavaScript won't warn you—it'll just produce NaN, which then infects every subsequent calculation:

let price = 100;
let discount; // forgot to assign a value

let total = price - discount; // NaN (undefined → NaN)
console.log(total);           // NaN — no error thrown!

With null, the bug is even sneakier because 0 might seem like a valid result:

let quantity = null; // maybe from missing database value
let itemPrice = 50;

let subtotal = quantity * itemPrice; // 0 (looks valid but isn't!)

The Asymmetry Problem

Notice the inconsistency: null pretending to be 0 can hide missing data, while undefined producing NaN at least signals something went wrong—though still silently.

Key Takeaway: In arithmetic, null coerces to 0 and undefined to NaN. Both conversions are silent, making it easy to miss bugs where missing values corrupt your calculations without throwing errors.