Problem Statement
Explain type coercion in JavaScript with examples. How do different operators handle it?
Explanation
Type coercion is JavaScript's automatic conversion of values from one data type to another. It happens when operators or comparisons are used with mixed types.
The plus operator performs string concatenation if either operand is a string, converting the other to string.
Other arithmetic operators like minus, multiply, divide always convert operands to numbers.
Comparison operators like double equals perform type coercion before comparing, while triple equals does not.
The logical operators OR and AND work with truthy and falsy values, using implicit boolean conversion.
Understanding coercion is crucial because it can cause unexpected bugs.
To avoid issues:
Use explicit conversion with Number, String, or Boolean functions. Always use triple equals for comparisons. Be careful with the plus operator when dealing with mixed types.
Code Solution
SolutionRead Only
// String coercion with +
console.log(5 + '5'); // '55' (number to string)
console.log('Hello' + true); // 'Hellotrue'
// Number coercion with other operators
console.log('10' - 5); // 5 (string to number)
console.log('10' * '2'); // 20
console.log('10' / '2'); // 5
console.log('5' - true); // 4 (true becomes 1)
// Boolean coercion
console.log(!'hello'); // false (string is truthy)
console.log(!0); // true (0 is falsy)
// Comparison coercion
console.log(5 == '5'); // true (coerces types)
console.log(5 === '5'); // false (no coercion)
console.log(null == undefined); // true (special case)
// Explicit conversion
console.log(Number('42')); // 42
console.log(String(42)); // '42'
console.log(Boolean(0)); // false
// Tricky examples
console.log('5' + 3 - 2); // 51 ('53' - 2)
console.log([] + []); // '' (empty string)
console.log([] + {}); // '[object Object]'
console.log({} + []); // '[object Object]'