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

Continue Learning with Java Guides

Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.

By Ramesh Fadatare - Udemy Instructor Partner

Comments