Type Coercion
Overview
Type Coercion is JavaScript's automatic or hidden conversion of values from one data type to another.
JS is trying to be 'helpful' when you mix types, but this behavior causes some of the most infamous and hilarious bugs in web development.
Syntax
If JS sees a + and a string, it converts everything to strings and glues them together. For -, *, and /, it tries to convert strings to numbers.
// The '+' operator prefers Strings
console.log(1 + "2"); // "12" (Number becomes String)
console.log("5" + 1); // "51"
// The '-' operator prefers Math
console.log("5" - 1); // 4 (String becomes Number)
console.log("5" * "2");// 10Always use === (Strict Equality) to avoid bugs. It checks both the value AND the data type.
console.log(1 == "1"); // true (Loose equality triggers coercion)
console.log(1 === "1"); // false (Strict equality blocks coercion)Common Pitfalls
- Using
==instead of===.0 == falseis true,"" == falseis true, and[] == falseis true. This leads to absolute chaos in large apps.
Interview Questions
Explicit coercion is when developers manually convert types, like using Number('5'). Implicit coercion happens automatically under the hood when JS tries to evaluate an expression with mixed types, like '5' - 1.
Real-World Example
When grabbing input from an HTML form, the value is ALWAYS a string, even if the user typed numbers. If you try to add it without explicit coercion, you create a bug.
const userAge = document.getElementById("ageInput").value; // "20"
// Bug! Output is "205"
const targetAge = userAge + 5;
// Fix using explicit coercion
const fixedAge = Number(userAge) + 5; // 25Check Your Knowledge
Test your understanding of Type Coercion with these quick questions.