The Empty String to Number Coercion
You'll learn why an empty string becomes 0 when JavaScript converts it to a number, and how this causes surprising behavior.
The Unexpected Zero
When JavaScript needs to convert an empty string ('') to a number, it produces 0. This is one of the most counterintuitive coercion rules in the language.
Think of it like this: JavaScript sees an empty string as "nothing written down," and mathematically interprets "nothing" as zero rather than as "not a number."
Why This Causes Problems
Because '' coerces to 0, you can end up with confusing comparisons and arithmetic:
'' == 0 // true (empty string coerces to 0)
'' === 0 // false (strict equality prevents coercion)
'' - 5 // -5 (empty string becomes 0, then 0 - 5)
'' * 10 // 0 (empty string becomes 0)
The arithmetic operators (except +) trigger numeric coercion, so the empty string silently becomes 0 before the operation happens.
Common Gotchas
This rule creates particularly nasty bugs when you have empty user input:
let userAge = ''; // User left field blank
if (userAge) {
// This block runs! Empty string is falsy, so we skip
}
if (userAge == 0) {
// This is TRUE — empty string coerces to 0
// Misleading: user didn't enter 0, they entered nothing!
}
The empty string is falsy in boolean context but coerces to 0 in numeric context—two completely different behaviors depending on how you use it.
Key Takeaway: The empty string '' coerces to 0 in numeric contexts, leading to confusing comparisons like '' == 0 being true and unexpected arithmetic results. Always use strict equality (===) and validate empty strings explicitly.