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:
Example
Create an array named “array”:
Now, create an empty array “arr” where the elements copied from the array “array”:
Invoke the “slice()” method on “array” and store elements in an empty array “arr”:
Print the resultant copied array on the console:
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:
Example
Use the spread operator with “array” to copy elements from the array and store them in an empty array “arr”:
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:
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.