Recognizing Implicit Coercion Sites
You'll learn: How to spot the common places in your code where JavaScript automatically converts values from one type to another without you explicitly asking.
What Are Coercion Sites?
A "coercion site" is any location in your code where JavaScript performs automatic type conversion. Think of these as checkpoints where JavaScript says, "I need a different type here, so I'll convert this value for you." Recognizing these spots helps you predict your code's behavior and avoid surprising bugs.
Common Implicit Coercion Sites
The + Operator
When one operand is a string, JavaScript coerces the other to a string:
"Score: " + 42 // "Score: 42" — number becomes string
Arithmetic Operators (-, *, /, %)
These always coerce operands to numbers:
"10" - 5 // 5 — string becomes number
Conditional Statements
If statements automatically coerce the condition to a boolean:
if ("hello") { } // "hello" coerced to true
Comparison Operators (==, !=)
Loose equality triggers coercion when types differ:
5 == "5" // true — string coerced to number
Logical Operators (&&, ||)
These evaluate truthiness, coercing values to boolean internally (but return the original operands):
0 || "default" // 0 is falsy, returns "default"
How to Spot Them
Look for mixing types: strings with numbers, objects in arithmetic, or non-booleans in conditions. Whenever types don't match what an operator "expects," coercion occurs.
Key Takeaway: Implicit coercion happens at predictable sites—string concatenation with +, arithmetic operators, conditionals, loose equality, and logical operators. Learning to recognize these patterns helps you write more predictable JavaScript.