👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!
In JavaScript , copying an array is not as easy as using the assignment operator (=) to create a duplicate . If you’ve tried this before, you’ll be surprised to find that it only links to the original list. What is the problem ?
In this guide, we will explain how to copy a JavaScript array. We’ll take a look at the code for three JavaScript array copying strategies so you can get started copying arrays.
The problem with copying JavaScript arrays
At one level, the " = & Rdquo; The operator creates a copy of an array in a new variable . However, this is more of a pointer than a copy. This is because the "=" operator creates a reference to an original array. It does not create a duplicate of the existing table.
Let’s try to create a copy of an array using the assignment operator without any other code:
Our code returns:
It seems that our table has been copied. "Fruit" contains all the values ​​from our "berries" array .
Now let’s try to add an element to the "fruits" array folder:
We have added "Melon" to the fruit series. Next, we print the values ​​for " fruits " and " berries " to the console: