Subtracting Strings
You'll learn how JavaScript automatically converts strings to numbers when you use the - operator, and what happens when that conversion fails.
The Subtraction Operator Forces Number Coercion
Unlike the + operator (which concatenates strings), the - operator has only one job: subtraction. When JavaScript sees -, it knows you must be doing math, so it automatically coerces both operands to numbers.
This is why '5' - '2' gives you 3, not an error. JavaScript uses the ToNumber abstract operation on each string, converting them to the numbers 5 and 2 before performing subtraction.
When Coercion Fails: NaN
If either string cannot be converted to a valid number, you get NaN (Not a Number). For example:
'10' - '3' // 3 (both strings coerce to numbers)
'hello' - '5' // NaN ('hello' can't become a number)
'8' - 'world' // NaN ('world' can't become a number)
'20' - '0' // 20
The subtraction operator applies the same coercion rules you learned with the unary + operator. Empty strings become 0, whitespace-only strings become 0, and anything that isn't number-like becomes NaN.
'15' - '' // 15 (empty string → 0)
'7' - ' ' // 7 (whitespace → 0)
Why This Matters
This behavior can catch you off guard if you're working with user input or data from APIs that arrive as strings. Unlike +, which might silently concatenate, - will attempt number conversion — and produce NaN if it can't.
Key Takeaway: The - operator always coerces its operands to numbers, making '5' - '2' work as 3, but producing NaN when conversion fails.