Using Modern ES6 Spread Operator
const originalArray = [2,4,6,8,10] const clone = [...originalArray]
The spread operator
The spread operator is much more powerful and used in different scenarios than it seems in this situation.
const originalArray = [1,2,3,4,5] const clone = originalArray.slice()
Slice is generally used to get a subarray from a starting index to end index (not included).
const originalArray = [1,2,3,4,5] const clone = .concat(originalArray)
Concat is a very useful method to merge two iterable. In this way, we take an empty array and concatenate the original array into it. It creates a fresh copy of the array.
Mutable are those values that we can change once initialized like an object, array, function, etc.
Immutable objects are those objects which cannot be changed once initialized like primitive data types. It is important to note that we can only reference immutable types to the new value and the old value becomes garbage value.
Mutable objects are reference type objects which means if we copy mutable objects using
= operator they point to the same memory location.
Why we do not use
= assignment operator?
This is an interesting question.
Here is an example of what it means.
originalArray = [1,2,3,4,5] clone = originalArray #Here begins the problem clone = 100 console.log(originalArray) # [100,2,3,4,5] console.log(clone) #[100, 2,3,4,5]
I only changed the
clone object, how the
Here is the concept.
= operator only copy the reference of the
originalArray to the
clone. It means that they refer to the same array in the memory.
This is why we do not use the
= operator to copy mutable objects.
= operator works only to copy immutable items.
Spread operator create Shallow copy
What do you think about cloning this array [[1,2,3], [4,5,6], [7,8,9]].
Can we use the spread operator to create a copy of this array?
This is an important use case to understand because you will face this problem frequently when dealing with the spread operator.
Note that the spread operator only copies the values at one level. That means the nested items will still be a reference type array.
Here is an example that describes the same.
const originalArray = [[1,2,3], [4,5,6], [7,8,9]] const clone = [...originalArray] clone = 10 clone = 77 #clone = [10, [77,5,6], [7,8,9]] #originalArray = [[1,2,3], [77,5,6], [7,8,9]]
Now you can see this problem in action.
The spread operator only copies one level of iterable. The other nested items are still referenced types or mutable.
All the ways mentioned above are good to use in any project. I personally prefer the spread operator because it works efficiently and the syntax is clean.
You can also go for
slice as you see fit.
If you have any problem or suggestion then feel free to ask in the comments.