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

ToNumber Abstract Operation

Understanding how JavaScript's internal ToNumber algorithm converts different types to numbers.

ToNumber Abstract Operation

You'll learn how JavaScript's internal ToNumber algorithm decides what numeric value each type should become during coercion.

What Is ToNumber?

When you learned about the unary + operator for number conversion, you used JavaScript's ToNumber abstract operation without realizing it. This is an internal algorithm (not a function you can call directly) that JavaScript uses behind the scenes whenever it needs to convert a value to a number.

Think of ToNumber as a universal translator that speaks every JavaScript type's language and translates them all into numbers.

How ToNumber Converts Different Types

Here's what happens internally for each type:

  • undefined → NaN
  • null → 0 (a famous quirk!)
  • true → 1, false → 0
  • Numbers → returned unchanged
  • Strings → parsed as numeric literals; whitespace is trimmed; empty/whitespace-only strings become 0; invalid formats become NaN
+undefined;     // NaN
+null;          // 0
+true;          // 1
+false;         // 0
+"42";          // 42
+"  99  ";      // 99 (whitespace trimmed)
+"";            // 0 (empty string)
+"hello";       // NaN (invalid number format)

Notice how ToNumber is very forgiving with strings—it trims whitespace and treats empty strings as zero, but rejects anything that doesn't look like a number.

Why This Matters

Understanding ToNumber helps you predict coercion behavior in arithmetic operations, comparisons, and explicit conversions. It's the reason null weirdly becomes 0 and undefined becomes NaN.

Key Takeaway: The ToNumber abstract operation is JavaScript's internal rulebook for converting any value into a number, with specific (sometimes surprising) results for each type.