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" - 3 → 2.
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
1// Explicit conversion2console.log(Number("42")); // 423console.log(Number("")); // 04console.log(Number("hello")); // NaN5console.log(Number(true)); // 16console.log(Number(null)); // 07console.log(Number(undefined)); // NaN89console.log(String(42)); // "42"10console.log(String(null)); // "null"11console.log(String(undefined)); // "undefined"1213console.log(Boolean(0)); // false14console.log(Boolean("")); // false15console.log(Boolean("0")); // true ⚠️16console.log(Boolean([])); // true ⚠️17console.log(Boolean({})); // true ⚠️1819// Implicit coercion20console.log("5" + 3); // "53" (string wins with +)21console.log("5" - 3); // 2 (- only works with numbers)22console.log("5" * "2"); // 1023console.log(true + true); // 224console.log(true + "1"); // "true1"2526// Double NOT for boolean conversion27console.log(!!0); // false28console.log(!!"hello"); // true29console.log(!!null); // false30console.log(!!undefined); // false31console.log(!!{}); // true
🏋️ Practice Exercise
Mini Exercise:
- Predict the output of each without running:
"" + 1 + 0,"" - 1 + 0,true + false,"3" > "12" - Write a function that converts any value to a boolean WITHOUT using
Boolean() - List all 8 falsy values in JavaScript from memory
- Explain why
[] == falseistruebut!![] === true
⚠️ Common Mistakes
Assuming
[]and{}are falsy — they are TRUTHY! Only 8 values are falsyUsing
+for addition when one operand might be a string — it concatenates insteadConfusing
Number('')(returns0) withNumber(' ')(also returns0) — whitespace is trimmedThinking
'3' > '12'compares numerically — string comparison is lexicographic, so'3' > '1'→trueNot 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.