Type System

Implicit Type Coercion

When JS operators encounter an invalid type, they attempt to convert the value to a valid type. This process of implicitly converting a type is called implicit type coercion. Consider the following:

let num1 = 9 * "3";
console.log(num1); // 27 (a number)
let num2 = 9 + "3";
console.log(num2); // "93" (a string)
  • Example 1: * can only be used for mathematical operations => 3 becomes a number
  • Example 2: + is overloaded. If there is a string it will attempt to concatenate => 9 becomes a string

Another weird instance is how == and != operators in boolean comparisons will attempt to convert anything to boolean.

false == ""; // true
false == "0"; // true
"" == "0"; // false
[0] == 0; // true

⚠️ Don't use implicit type coercion.

  • There are deterministic rules for the coercion, but its far too complex to be practical.
  • For boolean comparison, its best to use === and !==

Truthy / Falsy

When an expression expects a Boolean value, the following values are always treated as false => Falsy values: 

  • false (of course)
  • 0 (the number zero)
  • "" or '' (an empty string)
  • null
  • undefined
  • NaN (the result of failed mathematical operations)

Other values are Truthy.

© 2025 All rights reservedBuilt with Flowershow Cloud

Built with LogoFlowershow Cloud