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].

JavaScript
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

Similar Reads

Using the Array unshift() method

Adding new elements at the beginning of the existing array can be done by using the Array unshift() method. This method is similar to the push() method but it adds an element at the beginning of the array....

Using array.splice method

In this method, we will use an array.splice method. The array.splice() method is used to modify the content of the array....

Using the Spread operator

The Spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 value is expected....

Using Array concat() Method

The JavaScript Array concat() Method is used to merge two or more arrays together. This method helps to add new elements at the beginning of the array....

Using array destructuring

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....