The + operator is one of the most versatile — and most confusing — operators in JavaScript. It does two very different things depending on the types of its operands.
If both operands are numbers, it behaves like normal math:
1 + 2 // 3
10 + 5 // 15
3.5 + 1.5 // 5If any one operand is a string, + switches to string concatenation:
"1" + 2 // "12"
2 + "3" // "23"
"Hello" + " World" // "Hello World"JavaScript prefers strings when one side is already a string.
This is where it gets tricky — JavaScript tries to convert types automatically before applying +.
true + 1 // 2 (true → 1)
false + 1 // 1 (false → 0)
null + 1 // 1 (null → 0)
undefined + 1 // NaN (undefined → NaN)JavaScript calls an internal ToPrimitive conversion before + runs:
| Value | Converts To |
|---|---|
true |
1 |
false |
0 |
null |
0 |
undefined |
NaN |
Objects and arrays are converted to primitives (usually strings) before + is applied.
[1, 2] + [3, 4] // "1,23,4"
[] + [] // ""
[] + {} // "[object Object]"
{} + [] // 0 (in some contexts, {} is parsed as a block!)
[] + 1 // "1"
{} + 1 // 1Arrays convert to strings using .toString():
[1, 2].toString() // "1,2"
[3, 4].toString() // "3,4"
// So: "1,2" + "3,4" = "1,23,4"Objects convert to "[object Object]" by default:
({}).toString() // "[object Object]"JavaScript evaluates + expressions left to right, and the type of the first result determines what happens next.
1 + 2 + "3" // "33"
"1" + 2 + 3 // "123"// Example 1:
1 + 2 // → 3 (number + number)
3 + "3" // → "33" (number + string = string)
// Example 2:
"1" + 2 // → "12" (string + number = string)
"12" + 3 // → "123" (string + number = string)Tip: Parentheses can control evaluation order:
"1" + (2 + 3) // "15"
There's also a single (unary) + that converts a value to a number:
+"123" // 123
+"3.14" // 3.14
+"abc" // NaN
+true // 1
+false // 0
+null // 0
+undefined // NaN
+"" // 0
+" " // 0This is a quick and common way to convert strings to numbers in JavaScript.
const input = "42"
const num = +input // 42 (number)| Expression | Result | Reason |
|---|---|---|
1 + 2 |
3 |
Number + Number |
"1" + 2 |
"12" |
String operand → concatenation |
true + 1 |
2 |
true coerces to 1 |
null + 1 |
1 |
null coerces to 0 |
undefined + 1 |
NaN |
undefined coerces to NaN |
[] + [] |
"" |
Both arrays convert to "" |
[1,2] + [3,4] |
"1,23,4" |
Arrays stringify before concat |
1 + 2 + "3" |
"33" |
Left-to-right: 3 then "33" |
"1" + 2 + 3 |
"123" |
Left-to-right: "12" then "123" |
+"42" |
42 |
Unary + converts to number |
+"abc" |
NaN |
Can't convert to number |
Rule of thumb: When in doubt, explicitly convert types using
Number(),String(), orparseInt()instead of relying on JavaScript's implicit coercion.