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:
- 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
ToPrimitivealgorithm, typically callingvalueOf()and thentoString(). - 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. - Default to Numeric Addition: If
neither operand is a string, JavaScript converts both
operands to numbers using
ToNumberand performs standard mathematical addition.
Examples of Addition Coercion:
'5' + 3\(\rightarrow\)'53'(One operand is a string; triggers concatenation)true + 1\(\rightarrow\)2(Neither is a string;truebecomes1, then numeric addition occurs)null + 5\(\rightarrow\)5(nullconverts to0)undefined + 5\(\rightarrow\)NaN(undefinedconverts toNaN)[] + 1\(\rightarrow\)'1'(Empty array converts to"", triggering concatenation)
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:
- Convert to Primitives: Any object operands are
converted to primitive values using
ToPrimitivewith a number hint. - Convert to Numbers: JavaScript unconditionally
converts both operands to numbers using the
ToNumberalgorithm. - 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:
'5' - 2\(\rightarrow\)3(String'5'converts to number5)'10' - '4'\(\rightarrow\)6(Both strings convert to numbers)true - 1\(\rightarrow\)0(trueconverts to1)'hello' - 1\(\rightarrow\)NaN(String'hello'cannot be converted to a valid number)[5] - 2\(\rightarrow\)3([5]becomes'5', which converts to5)
Summary of Differences
+favors Strings: If any string is present (or produced by an object conversion), the operation results in a string. Otherwise, it defaults to a number.-strictly requires Numbers: Both operands are always coerced into numbers, producing either a valid mathematical result orNaN.