I wanted to add the elements of an array into another, so I tried this:
[1,2] + [3,4]
It responded with:
\"1,23,4\"
JavaScript's + operator has two purposes: adding two numbers, or joining two strings. It doesn't have a specific behaviour for arrays, so it's converting them to strings and then joining them.
If you want to join two arrays to produce a new one, use the .concat method instead:
[1, 2].concat([3, 4]) // [1, 2, 3, 4]
If you want to efficiently add all elements from one array to another, you need to use the .push method:
var data = [1, 2];
// ES6+:
data.push(...[3, 4]);
// or legacy:
Array.prototype.push.apply(data, [3, 4]);
// data is now [1, 2, 3, 4]
The behaviour of the + operator is defined in ECMA-262 5e Section 11.6.1:
11.6.1 The Addition operator ( + )
The addition operator either performs string concatenation or numeric addition. The production
AdditiveExpression : AdditiveExpression + MultiplicativeExpressionis evaluated as follows:
- Let
lrefbe the result of evaluatingAdditiveExpression.- Let
lvalbeGetValue(lref).- Let
rrefbe the result of evaluatingMultiplicativeExpression.- Let
rvalbeGetValue(rref).- Let
lprimbeToPrimitive(lval).- Let
rprimbeToPrimitive(rval).- If
Type(lprim)isStringorType(rprim)isString, then
- Return the String that is the result of concatenating
ToString(lprim)followed byToString(rprim)- Return the result of applying the addition operation to
ToNumber(lprim)andToNumber(rprim). See the Note below 11.6.3.
You can see that each operand is converted ToPrimitive. By reading further we can find that ToPrimitive will always convert arrays to strings, producing this result.