FreeCodeCamp and JavaScript: The concat() Method

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:

var alpha = [‘a’, ‘b’, ‘c’],
  numeric = [1, 2, 3];
var alphaNumeric = alpha.concat(numeric);
// Result: [‘a’, ‘b’, ‘c’, 1, 2, 3]

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:

var num1 = [1, 2, 3],
  num2 = [4, 5, 6],
  num3 = [7, 8, 9];
var nums = num1.concat(num2, num3);
console.log(nums); // Result: [1, 2, 3, 4, 5, 6, 7, 8, 9]

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:

var alpha = [‘a’, ‘b’, ‘c’];
var alphaNumeric = alpha.concat(1, [2, 3]);
// Result: [‘a’, ‘b’, ‘c’, 1, 2, 3]

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!

2 thoughts on “FreeCodeCamp and JavaScript: The concat() Method

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s