Array Destructuring In Javascript

Introduction

The new version of javascript has really great features to be working with arrays. The features make us code things faster with the new features. We can implement them in our varied kinds of applications with much ease. Let us see new features related to array one by one in detail.

Array Destructuring  

Array destructuring allows us to extract data and assign it to variables from array or objects. Using array destructuring we can assign values in the same way we initialize an array. Let us see an example of the same.
  • The syntax will be [ var 1, var 2, var 3] = array or { var1, var 2} = object
  • The values will be assign from left-to-right.
  • We can even assign values of objects to variables using destructuring.
let cars = ["AUDI" , "BMW" , "JAGUAR"];
let [x,y,z] = cars; // Array Destructuring
console.log(x); // AUDI
console.log(y); // BMW
console.log(z); // JAGUAR

Before array destructuring, we can achieve the same functionality with much more line of code as shown below:

let cars = ["AUDI" , "BMW" , "JAGUAR"];
let x = cars[0];
let y = cars[1];
let z = cars[2];

Now we will see how array destructuring works with spread operator(...).

let cars = ["AUDI" , "BMW" , "JAGUAR" , "FORD" , "HONDA"];
[a, b, ...rest] = cars;
console.log(a); // AUDI
console.log(b); // BMW
console.log(rest); // [  "JAGUAR", "FORD", "HONDA"]

Now we will see how we can optionally assign values from an array.

let cars = ["AUDI" , "BMW" , "JAGUAR" , "FORD"];
[a, b, , d] = cars; // As we left the third variable as blank here
console.log(a); // AUDI
console.log(b); // BMW
console.log(d); // FORD

We can even assign the values to an object using destructuring. Remember the keys name should be the same here.

let emp = {name: "AANCHAL", id: 2};
let {name, id} = emp;
console.log(name); // AANCHAL
console.log(id); // 2

We can even swap the values using the following technique:

let cars = ["AUDI" , "BMW" , "JAGUAR" , "FORD"];
[a, b] = cars;
[a, b]  = [b, a]; // Swapping of values 
console.log(a); // BMW
console.log(b); // AUDI

Comments