Type Conversion & Coercion

In JavaScript, values can be converted from one type to another. This happens in two ways:

  • Type Conversion: Manually converting a value using functions.
  • Type Coercion: Automatic conversion during operations.
Illustration of type_conversion_and_coercion
Illustration of type_conversion_and_coercion

💡 Key distinction

Type Conversion is explicit, controlled by the developer. Type Coercion happens implicitly during expression evaluation.

1. Type Conversion (Explicit)

You can explicitly convert types using built-in functions:

  • String(value) - converts to string
  • Number(value) - converts to number
  • Boolean(value) - converts to boolean

📌 Deep Dive: Explicit Conversion Examples

JAVASCRIPT
String(123);         // "123"
Number("456");         // 456
Boolean(0);            // false
Boolean("hello");      // true
Number("123abc");      // NaN (not a number)
Output
"123", 456, false, true, NaN

2. Type Coercion (Implicit)

JavaScript automatically converts types in some expressions, depending on the operator:

  • + operator concatenates if either operand is a string.
  • Other arithmetic operators convert operands to numbers.
  • Logical operators convert values to booleans.
Common Coercion Examples
ExpressionResult
"5" + 2"52" (string concatenation)
"5" - 23 (number subtraction)
1 + true2 (true → 1)
false + 11 (false → 0)
3 * "4"12 (string → number)
"6" / "2"3 (both strings → numbers)

⚠️ Watch out for unexpected coercion!

Operators like + can lead to surprising results if one operand is a string. Always be mindful of operand types to avoid bugs.

3. Falsy Values in Coercion

In boolean context, these values convert to false:

  • 0
  • "" (empty string)
  • null
  • undefined
  • NaN
  • false

All other values convert to true.

📌 Deep Dive: Boolean Coercion Examples

JAVASCRIPT
Boolean("");       // false
Boolean("0");      // true (non-empty string)
Boolean(null);     // false
Boolean([]);       // true (empty array)
Boolean({});       // true (empty object)
Output
false, true, false, true, true

Summary

  • Type Conversion: Use functions like String(), Number(), and Boolean() to convert explicitly.
  • Type Coercion: Happens automatically during operations; understand operator behavior to predict results.
  • Be cautious with + operator to avoid unexpected string concatenation.