Type Coercion
Type coercion is the automatic or implicit conversion of values from one data type to another (such as strings to numbers). Type conversion is similar to type coercion because they both convert values from one data type to another with one key difference — type coercion is implicit whereas type conversion can be either implicit or explicit.
1. Implicit Coercion
Implicit coercion happens when you apply operators to values of different types.
String Coercion
When the + operator is used with a string, it converts the other value to a string.
const x = 1 + "2"; // "12"
const y = "Hello " + 5; // "Hello 5"
Number Coercion
Mathematical operators other than + (like -, *, /, %) convert values to numbers.
const x = "5" - 2; // 3
const y = "10" * "2"; // 20
const z = "10" / 2; // 5
Boolean Coercion
Happens in logical contexts (like if statements) or with logical operators (||, &&, !).
Falsy Values:
false0""(empty string)nullundefinedNaN
All other values are Truthy.
if ("hello") {
console.log("This runs"); // "hello" is truthy
}
if (0) {
console.log("This won't run"); // 0 is falsy
}
2. Explicit Coercion
Explicit coercion is when you manually convert types using built-in functions.
Number("123"); // 123
String(123); // "123"
Boolean(1); // true
3. Equality Operators (== vs ===)
- Loose Equality (
==): Performs type coercion before comparing.1 == "1"; // true null == undefined; // true - Strict Equality (
===): Does NOT perform type coercion. Types must match.1 === "1"; // false null === undefined; // false
Best Practice: Always use === to avoid unexpected coercion bugs.
programming/javascript/vanilla/javascript programming/javascript/vanilla/data-types