by Sai gowtham

How to copy an array in JavaScript

How to copy an array in JavaScript

In this tutorial, we are going to learn about two different ways to copy or clone an array in JavaScript.

Slice method

The slice() method returns the copy of an array without modifying the original array in JavaScript.

Example:

const users = ['jim','raj','king'];

const users2 = users.slice() // creates the copy

console.log(users2) // ['jim','raj','king'];

Es6 spread operator (…)

In es6, we have a spread operator(…) which helps us to create a duplicate copy of an array.

Example:

const users = ['jim','raj','king'];

const users2 = [...users]// creates the copy

console.log(users2) // ['jim','raj','king'];

In the above code, we have added ...users inside users2 array so that all elements present inside the users array are copied to the users2 array.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
221,520 students enrolled
44 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
114,575 students enrolled
21 hours of video content
View Course