- By using the spread operator […]
- By using the Array.from() method
- By using the slice() method
Let’s explore each…
#1 – By using the spread operator […]
The spread operator allows us to make a copy of an array by spreading the values of the original array into a new one; this is handy when you need a duplicate array without referencing the original one. Here’s an example:
let originalArray = [1, 2, 3, 4, 5]; let clonedArray = [...originalArray];
How it works
The spread operator essentially takes the values from the original array and puts them into a new array. Because a new array is created, changes in the cloned array do not affect the original array.
- Step 1: Declare a variable named ‘originalArray’ and assign it an array of numbers.
- Step 2: Declare another variable, ‘clonedArray’. To clone ‘originalArray’, we use the spread operator inside a new array declaration. It spreads the elements of ‘originalArray’ into ‘clonedArray’.
- Step 3: Now ‘clonedArray’ is a copy of ‘originalArray’. Any changes to ‘clonedArray’ won’t affect ‘originalArray’ because they are now two separate arrays.
#2 – By using the Array.from() method
const arr1 = [1, 2, 3, 4]; const arr2 = Array.from(arr1);
How it works
The Array.from() function creates a new, shallow-copied array instance from an array-like or iterable object. In this case, we are creating a clone of ‘arr1’ and assigning it to ‘arr2’.
- First, we declare an array ‘arr1’ with the elements 1, 2, 3, and 4.
- Then we use Array.from() to create a new array ‘arr2’ that is a clone of ‘arr1’.
- The Array.from() function iterates over ‘arr1’ and assigns each value to a new array, ‘arr2’.
- Finally, ‘arr2’ is a separate instance and any changes to ‘arr1’ will not impact ‘arr2’, and vice versa.
#3 – By using the slice() method
let originalArray = [1, 2, 3, 4, 5]; let clonedArray = originalArray.slice();
How it works
The slice() method returns a shallow copy of a portion of an array into a new array object without modifying the original array. In this case, no start/end index is provided, so it copies the whole array.
- First, an array named ‘originalArray’ is defined with the values [1, 2, 3, 4, 5].
- Next, the slice() method is called on ‘originalArray’ without passing any arguments, which means it’s going to copy the entire array.
- As the slice() method does not mutate the original array but creates a new one, ‘clonedArray’ is a new array with the same elements as ‘originalArray’.
- As a result, you now have ‘clonedArray’ which is a clone of ‘originalArray’.
Remember, while it may seem trivial, proper array cloning is vital to prevent unexpected mutations in your code. By cloning arrays, we can ensure changes to the new array won’t affect the original one, enabling more secure, efficient, and cleaner code.