Type coercion is the implicit process of converting values from one type to another (such as string to number, object to boolean, and so on).
Coercion in computation
-
, *
, /
, %
- Operators that automatically converts to number
2 + true; // 3, because true is converted to 12 - false; // 2, because false is converted to 02 * "2"; // 410 / "2"; // 5
The addition sign is different on all these operators because it will prioritize concatenating strings rather than converting to number.
2 + "2"; // 222 - "2"; // 0
Coercion in conditional statements
Type coercion also happens when checking for truthy or falsy values.
let num = 10;
if (num) { console.log("num is truthy!"); // 10 is truthy so this condition will execute.}
let num = 0;
if (!num) { console.log("num is falsy!"); // 10 is falsy so this condition will execute.}