Concatenating arrays in JavaScript

So here’s an interesting thing I came across:

var arrays = [[1, 2, 3], [4, 5], [6]];
console.log(arrays.reduce(function(a, b){
return a + b;
}))

//1,2,34,56

I was playing around with Array.reduce and Array.concat, and started wondering what would happen if I tried to add up the total of all elements in the variable arrays.  I didn’t quite get what I was expecting.


var a = [1,2,3];
var b = [2,3,4];
console.log(a + b);

// 1,2,32,3,4

Apparently, the + operator acts to concatenate arrays. It recognizes commas, but the brackets confuse it somehow?

If anyone has a good explanation of this I’d love to hear it.

2 thoughts on “Concatenating arrays in JavaScript”

  1. That was pretty interesting :)

    Basically, Array.prototype</code doesn't support +. It does, however, contain the toString() method. And strings can be +'d together. Therefore it automatically coerces the arrays into strings.

    So, console.log(a + b) is equivalent to console.log(a.toString() + b.toString()).

    As for the initial question, to add all the elements in a 2d array, I would first reduce the 2d array into a 1d array using a.concat(b), then reduce that array to the sum of its elements.

    1. Thanks Prashanth! That explanation makes perfect sense. In this case, I would want to call console.log(a + ” ” + b) to get the desired result…. but I would then have to call .to_a?

Leave a Reply

Your email address will not be published. Required fields are marked *