Basic Destructuring JavaScript

Destructuring is a very useful feature of JavaScript, it is used to extract properties from objects to bind them to other variables. It can also be useful and less time-consuming because it allows you to extract many properties in a single statement while setting a default property if one doesn’t exist. In this post, we will learn about object destructuring in ES6.

The reason to destructure

var hero = {
name: 'Iron Man',
realName: 'Tony Stark'
};
var name = hero.name;var realName = hero.realName;
name; // => 'Iron Man',
realName; // => 'Tony Stark'

We can refactor the above code and destructure the code and make it more readable and easier to follow with the example below.

const hero = {
name: 'Iron Man',
realName: 'Tony Stark'
};
const { name, realName } = hero;
name; // => 'Batman',
realName; // => 'Bruce Wayne'

If we compare the different approaches to access the object properties we see the following differences.

const name     = hero.name;
const realName = hero.realName;
// is equivalent to:const { name, realName } = hero;

As you can see it is much easier to follow and read and also takes only one line of code. I’m sure you can see where this would come in handy especially with having more variables in the object.

Syntax of Extraction

const { identifier } = expression;
  • The identifier is where the name of the property to access
  • The expression evaluates to an object

After destructuring, the identifier contains the property value.

When extracting many properties we use commas in between each individual property like the example below.

const { identifier1, identifier2, ..., identifier100 } = expression;

Here’s the equivalent code:

const identifier1 = expression.identifier1;
const identifier2 = expression.identifier2;
// ...
const identifierN = expression.identifierN;

Default values

const hero = {
name: 'Iron Man',
realName: 'Tony Stark'
};
const { enemies } = hero;
partners; // => undefined

After we destructure the object calling the variable partners, we get undefined because we do not have a property in the object called partners. The good news is that we can set a default value even if the property doesn’t exist in the object. You do that with the following example.

const { identifier = defaultValue } = expression;

So in our example the code would look like this.

const hero = {
name: 'Batman',
realName: 'Bruce Wayne'
};
const { partners = ['Robin'] } = hero;
partners; // => ['Robin']

Now, instead of being undefined, the variable partners defaults to ['Robin'].

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store