Reputation: 33
Why does summing 2 arrays joins everything in a string, concatenating the first and last values:
let array = [1, 2]
let array2 = [3, 4]
let array3 = array + array2
console.log(array3) // 1,23,4
Upvotes: 1
Views: 384
Reputation: 3978
Because the +
operator acts diffently according to the type of the given operands.
In your example you may notice that:
array + array2 == array.toString() + array2.toString()
For further information you may read the docs and the spec
Upvotes: 3
Reputation: 13283
That's just how JavaScript works. Both are objects, there's not a defined thing for +
between an Array and an Array, so it does the default thing of converting to String and concatenating them (still as a String).
Use the Array.prototype.concat
method to acheive your goal.
let array = [1, 2]
let array2 = [3, 4]
let array3 = array.concat(array2);
console.log(array3) // [1, 2, 3, 4]
Alternatively, you can use the spread operator:
let array = [1, 2]
let array2 = [3, 4]
let array3 = [...array, ...array2];
console.log(array3) // [1, 2, 3, 4]
Upvotes: 4
Reputation: 13206
Javascript tries to be smart and figure out what you are trying to do. An addition sign implies adding two strings, so Javascript goes ahead and converts the arrays to strings first for you. How nice, right?
What you want to do is implement the concat method:
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2)
Upvotes: 1