How to clone array in ES6 ?

The spread operator in ES6 is used to clone an array, whereas slice() method in JavaScript is an older way that provide 0 as the first argument. These methods create a new, independent array and copy all the elements of oldArray to the new one i.e. both these methods do a shallow copy of the original array.

Syntax:

// Older way
var clonedArray= oldArray.slice(0)    

// ES6 way: spread operator
var clonedArrayES6= [...oldArray]    

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
  
// Cloning array using spread
// operator- ES6
  
const oldArray= ["dog1", "dog2", "dog3"];
   
const clonedArrayES6= [...oldArray];
   
// ["dog1", "dog2", "dog3"]
console.log(clonedArrayES6);  
</script>

chevron_right


Output:

Equality and sameness: Unlike “=” operator, which creates a new variable which just points to the original array instead of copying its elements, spread operator creates a new, cloned array, with different reference but same values. Hence “=” operator creates a deep copy of the original array but the spread operator does a shallow copy. The array created by the spread operator has the same value as that of the old array but, is not as same as the old array.



Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
// Equality and sameness in cloning array
  
const oldArray= ["dog1", "dog2", "dog3"];
  
const clonedArrayES6 = [...oldArray];
const newArray = oldArray;
  
// False, i.e. shallow copy
console.log(clonedArrayES6===oldArray)  
      
// True, i.e. deep copy
console.log(newArray === oldArray)  
</script>

chevron_right


Output:

Note: All the above examples can be tested by typing them within the script tag of HTML or directly into the browser’s console.

full-stack-img

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.