When One Becomes Another

In JS, types can change automatically, often in the most unexpected ways.

1. To String (String Conversion)

Happens when we need a text representation.

let value = true;
alert(String(value)); // "true"

2. To Number (Numeric Conversion)

Happens in mathematical expressions.

alert( "6" / "2" ); // 3, strings became numbers automatically!

Explicit conversion: Number(str). Special cases:

  • undefinedNaN
  • null0
  • true / false1 / 0
  • " 123 "123 (spaces at the edges are removed)

3. To Boolean (Boolean Conversion)

The most common conversion type.

  • ** " Falsy " values:** 0, "", null, undefined, NaN. They always turn into false.
  • Everything else: true.
Important

The string "0" and the string with a space " " are true. They are not empty. This is a common source of bugs.

Tip

A short way to turn something into a boolean is double negation: !!value.