Object-to-Number Coercion
What You'll Learn
You'll discover the exact two-step sequence JavaScript uses when converting objects to numbers: it tries valueOf() first, then falls back to toString().
The Two-Step Dance
When JavaScript needs to coerce an object to a number (like when you use the unary + or subtract from it), it follows a predictable pattern:
- First attempt: Call the object's
valueOf()method - If that doesn't return a primitive: Call the object's
toString()method - Then: Convert the resulting primitive to a number
Think of it like asking someone for their age: first you check if they have an ID card with a number (valueOf), and if not, you ask them to say it out loud (toString) and then interpret what they said as a number.
The Sequence in Action
Plain objects don't have a useful valueOf() — they just return themselves. So JavaScript moves to toString(), which gives "[object Object]". Converting that string to a number produces NaN.
Arrays follow the same pattern. Their valueOf() returns the array itself (not a primitive), so JavaScript calls toString(), which joins the array elements. An empty array becomes "", which coerces to 0. An array with one number becomes that number as a string, then a number.
Date objects are special: their valueOf() returns a primitive number (milliseconds since 1970), so that's used immediately — no toString() needed.
Why This Matters
Understanding this sequence helps you predict why +[] equals 0 (empty string → number) and why +{} equals NaN (weird string → invalid number). The valueOf() → toString() order is consistent and predictable once you know it.
Key Takeaway: When coercing objects to numbers, JavaScript always tries valueOf() first, then toString(), before finally converting the primitive result to a number.