cft

Copying Arrays In JavaScript (2022) | Deep walkthrough

Copying an Array can be a tricky task when it comes to JavaScript. What do I mean by it? Let’s not make things complicated. Imagine I have an array “arr1” and another variable named “arr2”, which is a copy of the original array.


user

Muhammad Taif Khan

2 years ago | 1 min read

A photo From RODNAE Productions on Pexels

Copying an Array can be a tricky task when it comes to JavaScript.

What do I mean by it? Let’s not make things complicated.

Imagine I have an array “arr1” and another variable named “arr2”, which is a copy of the original array.

let arr1 = [1,2,3,4,5];

let arr2 = arr1;

We copied the original array, Quite easy! isn’t it?

but wait…

Let’s try to change only the copied array “arr2” and see what happens.

arr2[1] = -7;

console.log(arr2); // outputs: [1,-7,3,4,5]

//print the original array

console.log(arr1); // outputs: [1,-7,3,4,5]

Did you notice something?

I only changed the copied array and the original array also changed. Why is that?

So arrays in Javascript are copied by “Reference”.

By “Reference”?? What does it mean?

Let me explain in simple words.

When each time you copy an array, The copied array holds a reference to the original array. So making changes to the copied array will make changes in the original array.

Then how we can copy an array without a reference?

There are multiple ways of doing so. I will use one of them here and will leave a link for more details so you can research further.

In order to copy an array without reference, we will use the Spread Operator.

The Spread Operator basically writes every element of the original array in the copied array.

let arr1 = [1,2,3,4,5];

let arr2 = [...arr1];

arr2[0] = -2;

console.log(arr2);// outputs : [-2,2,3,4,5]

console.log(arr1);// outputs : [1,2,3,4,5]

Now they are two independent arrays. Making changes to the copied array will not affect the original array.

Based on the types of elements in the array, we can use various techniques to deep copy. Here is the link to a very informative StackOverflow thread link.

Thanks for reading, for more informative and useful articles, follow me or support me by buying me a cup of coffee.

Upvote


user
Created by

Muhammad Taif Khan


people
Post

Upvote

Downvote

Comment

Bookmark

Share


Related Articles