What is type coercion
What is type coercion
Type coercion is when JavaScript converts a value from one type to another so that an operation can proceed. Coercion happens in two main ways: implicit and explicit. Implicit coercion occurs when operators or comparisons convert values automatically. Explicit coercion is when you convert values directly using Number, String, Boolean, or other APIs.
The language defines conversion rules for many operations. For arithmetic with the plus operator, if either operand is a string and the other is not an object with a special behavior, JavaScript converts the other operand to a string and concatenates. For subtraction, multiplication, and division,
JavaScript converts operands to numbers. For comparisons with double equals, the runtime attempts to convert both sides to a common type, which can lead to results that surprise people who are not aware of the rules.
Objects convert to primitives by trying valueOf and toString in a specific order depending on the operation. Symbols do not coerce to strings implicitly to avoid accidental leaks. Bigints do not mix with numbers without explicit conversion.
Examples
// string concatenation vs numeric addition
console.log("10" + 5); // "15"
console.log(10 + "5"); // "15"
console.log(10 - "5"); // 5
console.log("10" * "2"); // 20
// explicit coercion
console.log(Number("12")); // 12
console.log(String(7)); // "7"
console.log(Boolean("")); // false
console.log(Boolean("hi")); // true
// equality coercion
console.log(0 == false); // true
console.log("" == 0); // true
console.log(null == undefined); // true
console.log("0" == false); // true
// object to primitive
const price = {
value: 1000,
valueOf() {
return this.value;
},
};
console.log(price + 50); // 1050 (valueOf used)
Common misconceptions
- Coercion is always bad. Coercion is a tool; confusion comes from not knowing the rules. Use strict equality to avoid surprises where needed.
- The plus operator always adds numbers. If either side is a string, plus concatenates.
- Boolean conversion treats any non empty string as true but the string "0" is also true. Only the empty string is false.
Practice questions
- Show how different operators trigger coercion with examples for +, -, ==, and Boolean conversion.
- Explain how an object with a custom valueOf can influence arithmetic results.
- Why does 0 == false evaluate to true but 0 === false is false, and how would you make such comparisons safer.