Normalize input types
Convert external input before arithmetic or comparison.
JS Puzzles · Const
Type coercion is JavaScript's automatic or implicit conversion from one data type to another. It explains why operations such as addition may produce a string or number depending on the operands.
JavaScript may automatically convert a value when an operation expects another type. Primitive conversion uses the value's conversion rules, while object conversion consults Symbol.toPrimitive first and then valueOf() and toString().
const value = "5";
const implicit = value + 1;
const explicit = Number(value) + 1;
console.log(implicit, typeof implicit); // "51" string
console.log(explicit, typeof explicit); // 6 numberThe plus operator chooses string concatenation when either operand becomes a string; Number() makes the conversion explicit.
Convert external input before arithmetic or comparison.
Define how a domain object behaves in numeric or string contexts.
Make conversion intent visible in application code.
Type coercion is JavaScript's automatic or implicit conversion between data types. It commonly appears when an operation receives values whose types do not match the operation's expected type.
Follow-up: How can implicit coercion be avoided? Use explicit conversions such as Number(value) or String(value), and choose operators whose behavior is clear.
For object-to-primitive conversion, JavaScript first checks Symbol.toPrimitive. If that does not provide the result, it tries valueOf() and then toString(), using an order determined by the conversion hint.
Follow-up: What must Symbol.toPrimitive return? A primitive value; returning an object causes a TypeError.
Number(value) performs numeric conversion: null becomes 0, booleans become 1 or 0, undefined becomes NaN, and strings are parsed as numeric literals. A failed string parse produces NaN.
Follow-up: What special issue applies to BigInt conversion? Converting BigInt to Number can lose precision, and Number and BigInt cannot be mixed directly in operations.
Number()String()Boolean()Symbol.toPrimitivevalueOf()toString()BigInt()Number