String Coercion with the + Operator
What you'll learn: How the + operator automatically converts values to strings when one side is already a string.
The Magic of the Plus Sign
You already know the + operator adds numbers together. But when JavaScript sees a string on either side of the +, it switches gears completely: it converts the other operand into a string and glues them together (concatenation).
This automatic conversion is called string coercion. JavaScript is trying to be helpful — if you're mixing types with +, it assumes you want to build a string.
How It Works
"Hello" + 42
// Result: "Hello42"
100 + " bottles"
// Result: "100 bottles"
"The answer is " + true
// Result: "The answer is true"
Notice how 42 became "42", and true became "true". JavaScript coerced them into strings to match the string operand.
Think of It Like a Factory Line
Imagine the + operator as a factory worker. When materials (operands) arrive:
- Two numbers? Add them mathematically.
- At least one string? Convert everything to text and glue together.
The string "wins" — it forces the other value to become a string too.
Order Matters with Multiple Operations
1 + 2 + " items"
// Result: "3 items" (1+2=3, then "3"+" items")
"Total: " + 1 + 2
// Result: "Total: 12" (coerces left-to-right: "Total: 1", then "Total: 12")
Key Takeaway: When the + operator encounters a string on either side, it coerces the other operand to a string and concatenates instead of adding mathematically.