Computer >> Computer tutorials >  >> Programming >> Javascript

How to clone an array using spread operator in JavaScript?


Cloning is nothing but copying an array into another array. In olden days, the slice() method is used to clone an array, but ES6 has provided spread operator(...) to make our task easy. Lets' discuss both the methods.

Cloning using slice() method  

Example

In the following example slice() method is used to copy the array. slice() is used to slice the array from one index to another index. Since there is are no indexes provided the slice() method would slice the whole array. After slicing, the sliced part is copied into another array using assignment operator(=). 

<html>
<body>
   <script>
      const games = ['cricket', 'hockey', 'football','kabaddi'];
      const clonegames = games.slice();
      document.write(clonegames);
   </script>
</body>
</html>

Output

cricket,hockey,football,kabaddi


Cloning using spread operator

Es6 has brought many new features in which spread operator is a predominant one. This operator has many uses and cloning is one of those uses. 

Example

<html>
<body>
   <script>
      const games = ['cricket', 'hockey', 'football','kabaddi'];
      const clonegames = [...games];
      document.write(clonegames);
   </script>
</body>
</html>

Output

cricket,hockey,football,kabaddi