How to Copy an Array in JavaScript

📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.

🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.

▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

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