@daniloparrajr

Type coercion in JavaScript

  • 6/30/2022
  • 1 min read

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 1
2 - false; // 2, because false is converted to 0
2 * "2"; // 4
10 / "2"; // 5

The addition sign is different on all these operators because it will prioritize concatenating strings rather than converting to number.

2 + "2"; // 22
2 - "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.
}

Related Articles

JavaScript Hoisting

JavaScript hoisting refers to the interpreter moving the declarations of variables, functions, and classes to the top of their scope before execution.

  • 7/9/2022
  • 1 min read