Numeric Coercion with Arithmetic Operators
What you'll learn: How JavaScript automatically converts values to numbers when you use subtraction, multiplication, division, and remainder operators.
The Core Idea
While the + operator has special string behavior (as you learned in the previous lesson), the arithmetic operators -, *, /, and % have one clear job: perform math. When JavaScript sees these operators, it automatically tries to convert both operands into numbers before doing the calculation.
Think of it like a strict math teacher: if you hand them a word problem, they'll extract the numbers first before solving it. JavaScript does the same thing with these operators.
How It Works
When you use -, *, /, or %, JavaScript applies numeric coercion to both operands:
"10" - "5" // 5 (both strings converted to numbers)
"20" * "3" // 60
"100" / "4" // 25
"17" % "5" // 2
"8" - 2 // 6 (string converted to number)
12 * "3" // 36
true - false // 1 (true→1, false→0)
"5" * null // 0 (null→0)
What If Conversion Fails?
If JavaScript can't convert a value to a valid number, you get NaN:
"hello" - 5 // NaN
"10" * undefined // NaN
"abc" / 2 // NaN
Key Takeaway: The -, *, /, and % operators always attempt to convert their operands to numbers before performing arithmetic, unlike + which can concatenate strings. If conversion fails, the result is NaN.