Type coercion is JavaScript's automatic or implicit conversion of values from one data type to another. This usually happens when JavaScript tries to perform operations on values of different types.
JavaScript automatically converts types when needed.
console.log("5" + 3); // "53"
console.log("5" - 3); // 2
console.log("5" * 2); // 10
console.log("10" / 2); // 5
+ operator prefers string concatenation.
Values are converted to true or false in conditions.
Boolean(0); // false
Boolean(1); // true
Boolean(""); // false
Boolean("Hello"); // true
Boolean(null); // false
Boolean(undefined);// false
The == operator performs type coercion, while === does not.
console.log(5 == "5"); // true
console.log(5 === "5"); // false
=== to avoid unexpected results.
Explicit coercion happens when you manually convert types.
Number("10"); // 10
String(100); // "100"
Boolean(1); // true
Click the button to see type coercion results: