DEV Community

Cover image for Understanding Array.concat() in Javascript
Srijan
Srijan

Posted on • Originally published at hackinbits.com

Understanding Array.concat() in Javascript

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:

const fruits = ["apple", "orange", "kiwi"];
const vegetables = ["carrot", "tomato", "potato"];

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

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,

let watermelon = {
 name: "Watermelon",
 taste: "Sweet",
 shape: "round"
 };
Enter fullscreen mode Exit fullscreen mode

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"]

Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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.


This article was first published on hackinbits.com

Top comments (0)