Type Coercion
How JavaScript coerces types implicitly and best practices to avoid pitfalls.
Short explanation
JavaScript often converts values from one type to another automatically (coercion), which can lead to surprising results. Knowing coercion rules helps you avoid bugs and write clearer code.
Syntax example
console.log('5' - 1); // 4 (string -> number)
console.log('5' + 1); // '51' (number -> string concatenation)
console.log(0 == false); // true (loose equality coerces types)
console.log(0 === false); // false (strict equality checks type)
How JS handles it internally
The spec defines ToNumber, ToString, and ToPrimitive operations used during
coercion. Loose equality == follows complex rules to convert operands before
comparison; === avoids these conversions.
FAQ
Q: Should I use == or ===?
A: Prefer === to avoid coercion surprises unless you have a clear, documented
reason to use ==.