- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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>
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.
<html> <body> <script> const games = ['cricket', 'hockey', 'football','kabaddi']; const clonegames = [...games]; document.write(clonegames); </script> </body> </html>
- Using JSON.stringify() to display spread operator result?
- How to clone an element using jQuery?
- How to clone a canvas using FabricJS?
- Clone an ArrayList in Java