JavaScript - Type Conversions

Overview

Estimated time: 20–30 minutes

Convert values explicitly to avoid surprises. Be careful with implicit coercions.

Learning Objectives

  • Use Number(), String(), Boolean().
  • Parse numbers with radix and handle invalid input.
  • Recognize common implicit coercions.

Prerequisites

Explicit conversions

Number('42')      // 42
String(42)        // '42'
Boolean('')       // false
Boolean('text')   // true

Parsing numbers

parseInt('101', 2)   // 5 (binary)
parseInt('FF', 16)   // 255 (hex)
parseFloat('3.14')   // 3.14
Number('3.14')       // 3.14
Number('3.14px')     // NaN

Implicit coercions

'2' + 3   // '23' (string concatenation)
'2' * 3   // 6   (numeric coercion)
false == 0 // true (avoid ==; prefer ===)

Common Pitfalls

  • Using == relies on coercion rules; prefer === to avoid surprises.
  • parseInt without radix can misinterpret leading zeros in old environments; pass a radix.