0

Can you explain why the commas become the member of new array that is result of the sum of two arrays?

var array1 = [1,2]; var array2 = [3,4]; var newArray = array1 + array2; console.log(newArray.length); The result is 6

2nd Oct 2019, 5:46 AM
Nurman Tajir
Nurman Tajir - avatar
3 Answers
+ 3
Using the + operator to sum arrays most probably coerces the arrays into string and includes the commas between the elements in the string representation thats why it has a larger length. If you check the typeof the newArray you'll find it's a string. A better way is to use arr.concat(new).
2nd Oct 2019, 5:55 AM
xyz$
+ 2
You cannot use the + operator for arrays. This operator converts arrays into strings and concatenates them. Use concat: [1, 2].concat([3, 4])
2nd Oct 2019, 5:57 AM
Michael
Michael - avatar
+ 1
var array1 = [1,2]; var array2 = [3,4]; var newArray = [...array1, ...array2]; // I like do that // concat also works... array1 + array2 // This is simple join, "1,23,4" and have 6 characters.
2nd Oct 2019, 12:38 PM
JĂŽnatas Araripe
JĂŽnatas Araripe - avatar