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"]
Comments
Post a Comment
Leave Comment