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.
- Using slice() method
- 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
Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course