Skip to content

type coercion

Type coercion is the automatic conversion of a value from one data type to another, which JavaScript performs when an operator or built-in function receives a value of a type it doesn’t expect.

Coercion is implicit. Code that calls Number() or String() on purpose performs an explicit conversion, often called type conversion. ECMA-262 defines both through the same abstract operations, such as ToNumber, ToString, and ToBoolean. ToBoolean is the one that splits values into truthy and falsy.

The + operator concatenates when either operand is a string, while -, *, and / always do arithmetic, so they convert strings to numbers. The == operator coerces operands of different types before comparing them, such as a string to a number, and === never coerces.

When an operator receives an object, JavaScript first converts it to a primitive. It calls its [Symbol.toPrimitive]() method if it has one, passing a hint of "number", "string", or "default". Otherwise, it tries .valueOf() and .toString(), starting with .toString() only when a string is preferred.

Some coercions throw a TypeError instead. A symbol can’t be coerced to a number or a string, although an explicit String() call still works, and arithmetic that mixes a bigint with a number throws too.

Example

Say a shopping cart reads a quantity from a form field, which always arrives as a string, and adds or removes one item:

Language: JavaScript
> const quantity = "2";
undefined

> quantity + 1
'21'
> quantity - 1
1

> Number(quantity) + 1
3

> quantity == 2
true
> quantity === 2
false

The + operator sees a string, so it converts 1 to "1" and concatenates. The - operator only works on numbers, so it coerces "2" to 2. Calling Number() makes the intended addition explicit. Loose equality coerces the string to match the number, and strict equality doesn’t.

Say the cart stores a price as an object that prints as currency but calculates as a number. Its [Symbol.toPrimitive]() method shows which hint each operation passes:

Language: JavaScript
> const price = {
…   amount: 25,
…   [Symbol.toPrimitive](hint) {
…     return hint === "string" ? `$${this.amount}` : this.amount;
…   },
… };
undefined

> price * 2
50
> `Total: ${price}`
'Total: $25'
> price + 1
26

Multiplication asks for a number, and the template literal asks for a string. The + operator passes "default", so the method returns the number 25 and the addition produces the number 26.

To compare these conversions, pick a value for quantity and an expression, and see which operand gets converted before the operation runs:

Interactive diagram — enable JavaScript to view.

Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.


By Leodanis Pozo Ramos • Updated Nov. 17, 2026