Course contentsShow
← JavaScript
Lesson 293 of 2,7238. Type CoercionFree lesson

The + Operator's Dual Nature

Why + prefers string concatenation when either operand is a string, leading to '2' + 2 = '22'.

The + Operator's Dual Nature

You'll learn why the + operator behaves differently than other arithmetic operators, and why it favors strings over numbers.


Two Jobs, One Operator

In JavaScript, the + operator wears two hats: it can add numbers or concatenate (join) strings. This dual nature makes it unique among arithmetic operators. The rule is simple but crucial: if either operand is a string, + prefers concatenation over addition.

When JavaScript sees +, it checks both sides. If at least one value is a string, it converts the other value to a string and glues them together. Only when both values are non-strings does + perform numeric addition.

Why This Happens

Think of + as being "string-greedy." If strings are involved, it assumes you want to build text, not calculate. This is different from operators like -, *, or /, which always coerce values to numbers.

Examples:

'2' + 2      // '22' — string wins, numeric 2 becomes '2'
2 + '2'      // '22' — order doesn't matter
'Hello' + 5  // 'Hello5' — 5 becomes '5'
3 + 4 + '5'  // '75' — (3+4) first = 7, then 7 + '5' = '75'
'5' + 3 + 4  // '534' — '5'+3 = '53', then '53'+4 = '534'

Notice how in the last two examples, the order of operations matters. Once + encounters a string, everything that follows gets concatenated.


Key Takeaway: The + operator prefers string concatenation whenever either operand is a string, making it the only arithmetic operator with this "string-first" behavior. Always be mindful when mixing strings and numbers with +.