The +
operator produces the sum of numeric operands or string concatenation.
The +
operator produces the sum of numeric operands or string concatenation.
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:
TypeError
is thrown.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.
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.
Desktop | Mobile | Server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Opera | Safari | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | WebView Android | Deno | Node.js | ||
Addition |
1 | 12 | 1 | 3 | 1 | 18 | 4 | 10.1 | 1 | 1.0 | 4.4 | 1.0 | 0.10.0 |
© 2005–2023 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