Today we’re going to look at the concat() method. concat is short for concatenate and that’s exactly what it does, returning a new array that is the result of concatenating an array with another array, or even with a value.
As always, here’s the syntax, courtesy of MDN:
var new_array = old_array.concat(value1[, value2[, …[, valueN]]]);
The only parameters here are the various values. You need at least one – what’s the point of calling concat() if you don’t have at least two elements to join together? The rest, however, are optional.
Note that you get a brand new array back; the originals aren’t changed by the concat() method. That said, if you have an object in the new array, it will still refer to the same object as the original arrays, and so if you change the object, both the old array and the concatenated array will reflect those changes.
Let’s look at MDN’s examples:
So what we’re doing here is combining (concatenating) two arrays, one that consists of letters and one that consists of numbers. We get back an array that has the contents of both. Pretty simple. Let’s combine three arrays:
Same principle, except this time we gave it two arguments instead of just one. Let’s get a little more complex. Remember I said you could concatenate arrays AND values? Here’s an example:
We have an array of letters, an array of numbers, and a single value (1). We concatenate them all into one array.
And that’s it for the concat() method!