JavaScript Destructuring

Destructuring

Destructuring is a way to quickly extract data out of an {} or [] without having to write much code.

ES5 Way


// Assigning From Array to Local Variables
let direction = ["East", "West", "North", "South"];
let east = direction[0];
let west = direction[1];
let north = direction[2];
let south = direction[3];
console.log(east); // "East"

ES6 Way


let direction = ["East", "West", "North", "South"];
let [east, west, north, south] = direction;
console.log(east); // "East"

We can use this for object destructuring.


let math = {
  add: function(a, b) { return a + b; },
  sub: function(a, b) { return a - b; }
};

let {add, sub} = math;

add(2, 3);
sub(5, 3); 

Another use case is we can use also be used for passing objects into a function, allowing you to pull specific properties out of an object in a concise manner.


let a = { firstName: "A", lastName: "X" };
let b = { firstName: "B", lastName: "Y" };

function sayName({firstName, lastName, middleName = "N/A"}) {
  console.log(`Hello ${ firstName } ${ middleName } ${ lastName }`);  
}

sayName(a) //  Hello A N/A X
sayName(b) // Helo B Smith Y

About the Author: Pankaj Bisht