W3cubDocs

/JavaScript

Addition (+)

The addition operator (+) produces the sum of numeric operands or string concatenation.

Try it

Syntax

x + y

Description

The addition operator (+) is overloaded for two distinct operations: numeric addition and string concatenation. When evaluating, it would first coerce both operands to primitives by calling the object's [@@toPrimitive]() (with "default" as hint), valueOf(), and toString() methods, in that order. Then, if one side is a string, the other operand is also converted to a string and concatenated. Otherwise, both sides are converted to numbers (or, if they are BigInts, stay as BigInts), and numeric addition is performed.

String concatenation is often thought to be equivalent with template literals or String.prototype.concat(), but they are not. Addition would coerce the expression to a primitive, which calls valueOf() in priority; on the other hand, template literals and concat() would coerce the expression to a string, which calls toString() in priority. If the expression has a @@toPrimitive method, string concatenation calls it with "default" as hint, while template literals use "string". This is important for objects that have different string and primitive representations — such as Temporal, whose valueOf() method throws.

const t = Temporal.Now.instant();
"" + t; // Throws TypeError
`${t}`; // '2022-07-31T04:48:56.113918308Z'
"".concat(t); // '2022-07-31T04:48:56.113918308Z'

You are advised to not use "" + x to perform string coercion.

Examples

Numeric addition

// Number + Number -> addition
1 + 2 // 3

// Boolean + Number -> addition
true + 1 // 2

// Boolean + Boolean -> addition
false + false // 0

String concatenation

// String + String -> concatenation
'foo' + 'bar' // "foobar"

// Number + String -> concatenation
5 + 'foo' // "5foo"

// String + Boolean -> concatenation
'foo' + false // "foofalse"

Specifications

Browser compatibility

Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet Deno Node.js
Addition
1
12
1
3
3
1
4.4
18
4
10.1
1
1.0
1.0
0.10.0

See also

© 2005–2022 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Addition