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.
In this tutorial, we show you two ways to get the last element in an array using JavaScript.
  1. Using slice() method
  2. Using Es6 spread operator (…)

1. Using slice() method

The slice() method returns the copy of an array without modifying the original array in JavaScript.
Example:
const users = ['ramesh','tony','stark', 'vijay', 'prabhas'];

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

console.log(users1);
Output:
["ramesh", "tony", "stark", "vijay", "prabhas"]

2. Using Es6 spread operator (…)

In es6, we have a spread operator(…) which helps us to create a duplicate copy of an array.
Example:
const users = ['ramesh','tony','stark', 'vijay', 'prabhas'];

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

console.log(users1);
Output:
["ramesh", "tony", "stark", "vijay", "prabhas"]

All JavaScript Examples

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare