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.
Use the following syntax to copy an array by value with the help of the slice() method:
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:
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.
Follow the given syntax to copy the array by value using the spread operator:
Use the spread operator with “array” to copy elements from the array and store them in an empty array “arr”:
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.
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.
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.