Understanding Array.concat() method in Javascript

js

In Javascript, we use Array.concat() to concatenate/merge two or more arrays. Array.concat() returns a new array and does not modify the existing arrays.

Example:

1
2
3
4
5
const fruits = ["apple", "orange", "kiwi"];
const vegetables = ["carrot", "tomato", "potato"];

const fruitsAndVegetables = fruits.concat(vegetables);
// ["apple", "orange", "kiwi", "carrot", "tomato", "potato"]

If no parameters are passed on to the Array.concat() method, it returns the shallow copy of the existing array on which it is called.

Array.concat() on Object References

Before working on concatenating arrays, let's look into Object references.

Object Reference

In Javascript, Objects are a reference type. When you assign an object to a variable, variable store a reference to the object and not the object itself. For example,

1
2
3
4
5
let watermelon = {
 name: "Watermelon",
 taste: "Sweet",
 shape: "round"
 };

Here, variable watermelon stores a reference to the assigned object. Now, let's store it into the fruit array and use Array.concat() over it.

1
2
3
4
5
const fruits = ["apple", "orange", "kiwi", watermelon];
const vegetables = ["carrot", "tomato", "potato"];

const fruitsAndVegetables = fruits.concat(vegetables);
// ["apple", "orange", "kiwi", {…}, "carrot", "tomato", "potato"]

Here, Watermelon is shallowly copied and the reference to the original object is only copied and not the object itself. Now, the watermelon in both the fruits array and the fruitsAndVegetables array are pointing to the same object. So, if any value of the watermelon object is changed, it will be changed in fruitsAndVegetables array as well.

Array.concat on primitive data types

Array.concat() copies values of primitive data types such as string, number, and boolean into the new array.

1
2
3
4
let mixedArray1 = ["str", true, 1];
let mixedArray2 = ["str2" , false, 5];
let newMixedArray = mixedArray1.concat(mixedArray2);
// ["str", true, 1, "str2", false, 5]

Concatenating multiple arrays

To concatenate multiple arrays, we call Array.concat() on one array and pass the rest arrays as arguments.

1
2
3
4
5
6
const num1 = [ 1, 2, 3];
const num2 = [ 4, 5, 6];
const num3 = [ 7, 8, 9];

const num = num1.concat(num2, num3);
// [1, 2, 3, 4, 5, 6, 7, 8, 9]

We will love to see examples and scenarios where you have used Array.concat(). Feel free to add them in the comments below :). Have a nice day.

Share and support us

Share on social media and help us reach more people