Type Conversion & Coercion

📖 Concept

Type Conversion (explicit) is when YOU intentionally convert a value: Number("42"), String(42), Boolean(0).

Type Coercion (implicit) is when JAVASCRIPT automatically converts types during operations: "5" + 3"53", "5" - 32.

Understanding coercion rules is crucial for debugging and interviews:

  • To String: + with a string converts the other operand to string
  • To Number: -, *, /, % convert strings to numbers; + before a value is unary plus
  • To Boolean: Values are either truthy or falsy

Falsy values (only 8): false, 0, -0, 0n, "", null, undefined, NaN Everything else is truthy — including [], {}, "0", "false"!

🏠 Real-world analogy: Coercion is like auto-translate — sometimes it gets the meaning right, sometimes hilariously wrong. Explicit conversion is using a professional translator.

💻 Code Example

codeTap to expand ⛶
1// Explicit conversion
2console.log(Number("42")); // 42
3console.log(Number("")); // 0
4console.log(Number("hello")); // NaN
5console.log(Number(true)); // 1
6console.log(Number(null)); // 0
7console.log(Number(undefined)); // NaN
8
9console.log(String(42)); // "42"
10console.log(String(null)); // "null"
11console.log(String(undefined)); // "undefined"
12
13console.log(Boolean(0)); // false
14console.log(Boolean("")); // false
15console.log(Boolean("0")); // true ⚠️
16console.log(Boolean([])); // true ⚠️
17console.log(Boolean({})); // true ⚠️
18
19// Implicit coercion
20console.log("5" + 3); // "53" (string wins with +)
21console.log("5" - 3); // 2 (- only works with numbers)
22console.log("5" * "2"); // 10
23console.log(true + true); // 2
24console.log(true + "1"); // "true1"
25
26// Double NOT for boolean conversion
27console.log(!!0); // false
28console.log(!!"hello"); // true
29console.log(!!null); // false
30console.log(!!undefined); // false
31console.log(!!{}); // true

🏋️ Practice Exercise

Mini Exercise:

  1. Predict the output of each without running: "" + 1 + 0, "" - 1 + 0, true + false, "3" > "12"
  2. Write a function that converts any value to a boolean WITHOUT using Boolean()
  3. List all 8 falsy values in JavaScript from memory
  4. Explain why [] == false is true but !![] === true

⚠️ Common Mistakes

  • Assuming [] and {} are falsy — they are TRUTHY! Only 8 values are falsy

  • Using + for addition when one operand might be a string — it concatenates instead

  • Confusing Number('') (returns 0) with Number(' ') (also returns 0) — whitespace is trimmed

  • Thinking '3' > '12' compares numerically — string comparison is lexicographic, so '3' > '1'true

  • Not knowing that == triggers complex coercion rules — always use === to avoid surprises

💼 Interview Questions

🎤 Mock Interview

Mock interview is powered by AI for Type Conversion & Coercion. Login to unlock this feature.