JavaScript Type Coercion in Addition and Subtraction

JavaScript uses implicit type coercion to automatically convert operand data types during operations, but it evaluates addition (+) and subtraction (-) through fundamentally different rules. While the subtraction operator strictly enforces numeric conversion, the addition operator is overloaded to support both numeric arithmetic and string concatenation. Understanding these underlying evaluation steps clarifies why operations like '5' + 2 result in '52' while '5' - 2 yields 3.

The Addition Operator (+)

The addition operator determines its behavior based on the primitive types of its operands. When evaluating an expression with +, JavaScript executes the following steps:

  1. Convert to Primitives: If either operand is an object (such as an array or object literal), JavaScript converts it to a primitive value using the internal ToPrimitive algorithm, typically calling valueOf() and then toString().
  2. Check for Strings: If either operand is a string (or becomes a string after primitive conversion), JavaScript treats the operation as string concatenation. The other operand is implicitly converted to a string using ToString, and the two strings are joined.
  3. Default to Numeric Addition: If neither operand is a string, JavaScript converts both operands to numbers using ToNumber and performs standard mathematical addition.

Examples of Addition Coercion:

The Subtraction Operator (-)

Unlike addition, the subtraction operator has no secondary purpose like concatenation. It is exclusively an arithmetic operator.

When JavaScript processes the - operator:

  1. Convert to Primitives: Any object operands are converted to primitive values using ToPrimitive with a number hint.
  2. Convert to Numbers: JavaScript unconditionally converts both operands to numbers using the ToNumber algorithm.
  3. Perform Math: The arithmetic subtraction is executed. If either operand cannot be parsed into a valid number, the operation results in NaN (Not-a-Number).

Examples of Subtraction Coercion:

Summary of Differences