DEV Community

jaepass
jaepass

Posted on • Updated on

Learning Destructuring

What exactly is the new feature destructuring in ES6?

Destructuring helps to break up your code by giving it the pattern you are expecting to get back. It aims to make your code more readable. Destructuring is an assignment task, not a declarative task.

Lets look at the different between the regular imperative way and with ES6 destructuring technique:

function someData() {
  return [dog, cat, fish];
}

var tmp = someData();
var first = returnedData[0];
var second = returnedData[1];
var third = returnedData[2];

We now take the same logic and implement with ES6 destructuring:

function someData() {
  return [dog, cat, fish];
}

var [
  first,
  second,
  third] 
= someData();

If you want to define a default value, you can use a default value expression for the destructured method:

var [
  first,
  second = 10,
  third
] 
= someData();

Whereas, prior to ES6, you would implement your default value as such:

var second = returnedData[1] !== undefined ? returnedData[1] : 10;

Top comments (0)