24. Type Coercion
Type Coercion is JavaScript's automatic, implicit conversion of values from one data type to another (e.g., number to string, string to boolean).
This behavior is often a source of bugs for beginners.
Coercion to String
When the + operator is used with a string and another type, JS converts the other type to a string and concatenates.
javascript console.log(5 + ' apples'); // Output: '5 apples' console.log('Value: ' + true); // Output: 'Value: true'
Coercion to Number
When mathematical operators (like -, *, /) are used, JS attempts to convert strings to numbers.
javascript console.log('10' / 2); // Output: 5 (String '10' is coerced to Number 10) console.log('10' - 5); // Output: 5 console.log('10' * '2'); // Output: 20 console.log('hello' - 5); // Output: NaN (Cannot coerce 'hello' to a number)
Coercion to Boolean
Used in logical tests (like if statements). All values convert to either true or false (truthy/falsy, revisited later).