Type Coercion in JavaScript

Type coercion is the automatic or implicit conversion of values from one data type to another. Understanding coercion is crucial for avoiding unexpected behaviors in JavaScript.

Implicit vs Explicit Coercion

// Implicit coercion
"5" + 3    // "53" (string)
"5" - 3    // 2 (number)
5 + true   // 6 (number)
10 + false // 10 (number)

// Explicit coercion
Number("5")     // 5
String(123)     // "123"
Boolean(1)      // true
parseInt("123") // 123

Truthy and Falsy Values

// Falsy values
console.log(Boolean(false))     // false
console.log(Boolean(0))         // false
console.log(Boolean(""))        // false
console.log(Boolean(null))      // false
console.log(Boolean(undefined)) // false
console.log(Boolean(NaN))       // false

// Truthy values
console.log(Boolean(true))      // true
console.log(Boolean(1))         // true
console.log(Boolean("hello"))   // true
console.log(Boolean([]))        // true
console.log(Boolean({}))        // true
console.log(Boolean(function(){})) // true

Equality Comparisons

// Double equals (with coercion)
null == undefined   // true
"0" == false       // true
1 == true          // true
[] == false        // true
"" == 0            // true

// Triple equals (no coercion)
null === undefined  // false
"0" === false      // false
1 === true         // false
[] === false       // false
"" === 0           // false

Common Gotchas

// Array operations
[] + []           // "" (empty string)
[] + {}           // "[object Object]"
{} + []           // 0 (in some browsers)

// Number coercion
1 + "2" + 3       // "123"
1 + 2 + "3"       // "33"
+"42"             // 42 (number)
-"42"             // -42 (number)

// Boolean operations
!!"hello"         // true
!!""             // false
!![]             // true
!!0              // false

Common Interview Follow-up Questions

  1. Why should you use === instead of ==?
  2. How does JavaScript coerce values in boolean contexts?
  3. What are the rules for + operator with different types?
  4. How does Array.prototype.join() handle type coercion?

Best Practices

  • Use === for equality comparisons
  • Explicitly convert types when needed
  • Be careful with mathematical operations on strings
  • Understand falsy values in conditional statements
  • Use Boolean() for explicit boolean conversion