Course contentsShow
← JavaScript
Lesson 240 of 2,7237. Arithmetic and OperatorsFree lesson

Operator Overloading: The + String Caveat

Recognize how + concatenates strings when either operand is a string, causing type coercion surprises.

Operator Overloading: The + String Caveat

What you'll learn: How the + operator behaves differently when strings are involved, often causing unexpected type conversions.

The Special Behavior of +

In JavaScript, the + operator wears two hats: it adds numbers and concatenates (joins) strings. When you use + with two numbers, you get addition. But here's the catch: if either operand is a string, JavaScript assumes you want concatenation and converts the other value to a string too.

This automatic conversion (called type coercion) can create surprises:

5 + 3        // 8 (both numbers → addition)
"5" + 3      // "53" (string + number → concatenation)
5 + "3"      // "53" (number + string → concatenation)
"Hello" + 5  // "Hello5" (string wins)

Even with multiple operands, once a string enters the mix, everything from that point becomes concatenation:

1 + 2 + 3       // 6 (all numbers)
1 + 2 + "3"     // "33" (adds 1+2 first, then concatenates with "3")
"1" + 2 + 3     // "123" (string first, so everything concatenates)

Why This Matters

This behavior is unique to +. Other arithmetic operators (-, *, /, %, **) always try to convert values to numbers:

"10" - 5    // 5 (string coerced to number)
"10" + 5    // "105" (number coerced to string!)

Analogy: Think of + as overly polite—if it sees a string, it assumes everyone wants to be a string. The other operators are strict mathematicians who only speak numbers.

Key Takeaway: When using the + operator, if either operand is a string, JavaScript performs string concatenation instead of addition, converting the other value to a string—watch out for unexpected "105" instead of 15!