

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Questions & Answers
- How to clone an object using spread operator in JavaScript?
- How to find maximum value in an array using spread operator in JavaScript?
- JavaScript Spread Operator
- What is spread Operator (...) in JavaScript?
- Spread operator for arrays in JavaScript
- Spread operator in function calls JavaScript
- Using JSON.stringify() to display spread operator result?
- How to clone an object in JavaScript?
- Usage of rest parameter and spread operator in JavaScript?
- How to clone an element using jQuery?
- How to use spread operator to join two or more arrays in JavaScript?
- How to clone a Date object in JavaScript?
- How to clone a canvas using FabricJS?
- Clone an ArrayList in Java
- Rest and Spread operators in JavaScript
Advertisements