Understanding Array.concat() method in Javascript


Table of Contents

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,

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.

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.

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.

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 this

Share on social media