Understand implicit coercion — when JavaScript converts types automatically — and explicit casting using Number(), String(), Boolean(), parseInt(), and more.
Why: JavaScript automatically converts types when operators receive mismatched operands. This can lead to surprising results — knowing the rules prevents bugs.
// + with a string converts to string
console.log('5' + 1); // '51' — number coerced to string
console.log(1 + '5'); // '15'
// -, *, / convert strings to numbers
console.log('5' - 1); // 4
console.log('6' * '2'); // 12
// Loose equality coerces types
console.log(0 == false); // true
console.log('' == false); // true
console.log(null == undefined); // true
console.log(null == 0); // false
// Boolean coercion
console.log(Boolean(0)); // false
console.log(Boolean('')); // false
console.log(Boolean([])); // true — empty array is truthy!
console.log(Boolean(null)); // falseWhy: explicit conversion makes intent clear and avoids coercion surprises. Use Number(), String(), Boolean(), parseInt(), parseFloat() at system boundaries.
// To number
console.log(Number('42')); // 42
console.log(Number('')); // 0
console.log(Number('abc')); // NaN
console.log(parseInt('42px')); // 42 — stops at non-numeric
console.log(parseFloat('3.14 items')); // 3.14
// To string
console.log(String(42)); // '42'
console.log(String(null)); // 'null'
console.log((255).toString(16)); // 'ff' — hex
// To boolean
console.log(Boolean(1)); // true
console.log(Boolean(0)); // false
console.log(Boolean('hello')); // true
console.log(Boolean(null)); // false
// !! shorthand for boolean conversion
console.log(!!0); // false
console.log(!!'hi'); // true