Unexpected Type Coercion
Quick summary
JavaScript converted a value to a different type automatically, causing your code to behave differently than expected.
Why this happens
Using == instead of === (loose equality coerces types)
Using + with mixed types (string + number concatenates)
Using truthy/falsy values in conditions without understanding the rules
Minimal example
console.log(0 == ""); // true — coercion!
console.log(null == undefined); // true — coercion!
console.log("5" + 3); // "53" — concatenation!console.log(0 === ""); // false — no coercion
console.log(null === undefined); // false
console.log(Number("5") + 3); // 8 — explicit conversionLoose equality (==) coerces types before comparing, leading to surprising results. Strict equality (===) compares without coercion. Explicit type conversion makes the intent clear.
How to diagnose
Check if the result type matches what you expect
Use typeof to inspect the actual types of operands
Replace == with === to see if coercion was the issue
How to fix
Use === instead of == to avoid implicit coercion
Explicitly convert types with Number(), String(), Boolean()
Use the same type on both sides of operations
How to prevent
Always use === and !== instead of == and !=
Explicitly convert types instead of relying on coercion
Related Resources
Related Glossary
Related Lessons
- Data Types
Learn about type coercion.