Type Coercion & typeof
JavaScript automatically converts types in certain situations — '5' + 3 gives '53' (string), but '5' - 3 gives 2 (number). Understanding type coercion prevents subtle bugs that catch even experienced developers.
Type Coercion Rules
- + with a string — converts everything to string: '5' + 3 = '53' (concatenation, not addition)
- - * / with strings — converts to numbers: '5' - 3 = 2, '10' * 2 = 20
- Boolean context — false, 0, -0, 0n, '', null, undefined, NaN are FALSY (7 values). Everything else is TRUTHY
- == vs === — == does type coercion: '5' == 5 is true. === checks type too: '5' === 5 is false
- Number() — Explicit conversion: Number('42') = 42, Number('hello') = NaN
- String() — Explicit conversion: String(42) = '42', String(true) = 'true'
- Boolean() — Explicit conversion: Boolean(0) = false, Boolean('hello') = true
Type Coercion Examples
// Implicit coercion (automatic — watch out!)
console.log("5" + 3); // "53" (string!)
console.log("5" - 3); // 2 (number!)
console.log("5" * 2); // 10 (number!)
console.log("hello" - 1); // NaN (can't subtract from text)
// == vs === (ALWAYS use ===)
console.log(5 == "5"); // true (coerces type)
console.log(5 === "5"); // false (strict — different types)
console.log(null == undefined); // true (loose)
console.log(null === undefined); // false (strict)
// Truthy / Falsy
console.log(Boolean(0)); // false
console.log(Boolean("")); // false
console.log(Boolean(null)); // false
console.log(Boolean(undefined)); // false
console.log(Boolean("hello")); // true
console.log(Boolean(42)); // true
console.log(Boolean([])); // true (empty array is truthy!)
// Explicit conversion (recommended)
const input = "42";
const num = Number(input); // 42
const str = String(100); // "100"Tip
Tip
Always use === (strict equality) instead of == (loose equality). The only useful case for == is checking null/undefined together: value == null catches both. For everything else, strict equality prevents unexpected coercion bugs.
Map for dictionaries. Object for records/config. WeakMap for metadata that shouldnt prevent GC.
Common Mistake
Warning
Writing if(value) to check if a variable has a value. This fails for valid falsy values like 0, '' (empty string), and false. Use value !== undefined or value !== null for existence checks when 0 or '' are valid inputs.
Practice Task
Note
Predict the output before running: (1) '10' + 5, (2) '10' - 5, (3) true + 1, (4) null + 5, (5) undefined + 5. Run each in the console and verify. Understanding these coercion results prevents real-world bugs.
Quick Quiz
Key Takeaways
- JavaScript automatically converts types in certain situations — '5' + 3 gives '53' (string), but '5' - 3 gives 2 (number).
- + with a string — converts everything to string: '5' + 3 = '53' (concatenation, not addition)
- * / with strings — converts to numbers: '5' - 3 = 2, '10' * 2 = 20
- Boolean context — false, 0, -0, 0n, '', null, undefined, NaN are FALSY (7 values). Everything else is TRUTHY