JavaScript

Copy an Array by Value – JavaScript

There are several reasons developers might want to copy an array by value in JavaScript, such as creating a new, independent copy of the array rather than just creating a new reference to the original array. This can be useful if you want to change the copy without affecting the original array.

This post will describe JavaScript’s methods to copy an array by value.

How to Copy an Array by Value Using JavaScript?

To copy an array by value, use the given mentioned methods:

Method 1: Copy an Array by Value Using slice() Method

For copying an array by value, use the “slice()” method. It gives the same elements in a new array without modifying the original array.

Syntax

Use the following syntax to copy an array by value with the help of the slice() method:

array.slice()

Example

Create an array named “array”:

var array =['HTML', 'CSS', 'JavaScript', 'Java'];

Now, create an empty array “arr” where the elements copied from the array “array”:

var arr = [];

Invoke the “slice()” method on “array” and store elements in an empty array “arr”:

arr = array.slice();

Print the resultant copied array on the console:

console.log("Copied array: ");

console.log(arr);

It can be seen that the array has been successfully copied into an empty array:

Method 2: Copy an Array by Value Using Spread Operator “…”

Use the ES6 feature Spread operator” for copying array elements by value from one array to another. It copies all the elements of an array quickly by reducing lines of code and enhancing the code readability.

Syntax

Follow the given syntax to copy the array by value using the spread operator:

[...array]

Example

Use the spread operator with “array” to copy elements from the array and store them in an empty array “arr”:

arr = [...array];

Output

Method 3: Copy an Array by Value Using “for” Loop

You can also use the standard “for” loop for copying elements of an array to another. It iterates through an array, copies each element, and stores it in an empty array.

Example

Iterate the array until its length and copy it in an empty array:

for(var i = 0, len = array.length; i < len; ++i){

arr[i] = array[i];

}

The output indicates that the array has been successfully copied into an empty array:

We have gathered all the necessary information related to copying arrays by value.

Conclusion

To copy an array by value, use the “slice()” method, “Spread operator”, or “for” loop. These methods copied array elements efficiently, whereas the spread operator is the simplest and best approach. This post described the methods to copy an array by value.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.