Addition (+)

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

Try it

Syntax

js

x + y

Description

The + operator is overloaded for two distinct operations: numeric addition and string concatenation. When evaluating, it first coerces both operands to primitives. Then, the two operands' types are tested:

  • If one side is a string, the other operand is also converted to a string and they are concatenated.
  • If they are both BigInts, BigInt addition is performed. If one side is a BigInt but the other is not, a TypeError is thrown.
  • Otherwise, both sides are converted to numbers, 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 coerces the expression to a primitive, which calls valueOf() in priority; on the other hand, template literals and concat() 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.

js

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

Number addition

js

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

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

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

BigInt addition

js

// BigInt + BigInt -> addition
1n + 2n; // 3n

// BigInt + Number -> throws TypeError
1n + 2; // TypeError: Cannot mix BigInt and other types, use explicit conversions

// To add a BigInt to a non-BigInt, convert either operand
1n + BigInt(2); // 3n
Number(1n) + 2; // 3

String concatenation

js

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

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

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

// String + Number -> concatenation
"2" + 2; // "22"

Specifications

Specification
ECMAScript Language Specification
# sec-addition-operator-plus

Browser compatibility

BCD tables only load in the browser

See also