How to use array destructuring In Javascript
Array destructuring can prepend elements to an array in JavaScript. Create a new array with the element to be added followed by spread operator and the original array. This forms the updated array with elements added at the beginning.
Example: In this example, the array [1, âŠarr] uses array destructuring to prepend the element 1 to the beginning of the arr array. After the operation, arr becomes [1, 2, 3, 4].
let arr = [2, 3, 4];
arr = [1, ...arr]; // arr is now [1, 2, 3, 4]
console.log(arr); // Output: [1, 2, 3, 4]
Output
[ 1, 2, 3, 4 ]
Add new elements at the beginning of an array using JavaScript
In this article, we will learn how to add new elements at the beginning of an array using JavaScript. We can do this by using the following methods:
Table of Content
- Using the Array unshift() method
- Using array.splice method
- Using the Spread operator
- Using Array concat() Method
- Using array destructuring
Contact Us