DEV Community

Subramanya Chakravarthy
Subramanya Chakravarthy

Posted on

Destructuring in JavaScript

Destructuring is introduced as one of the ES6 features. It plays an important role in everyday development as we all deal with objects and arrays. It improves readability of code

Let's say we have a object containing user details

let me = {
  name: 'chakravarthy',
  age: 23,
  social: ['twitter', 'github', 'medium'],
  props: {
    height: 180,
    weight: 63,
  },
  comments: [
    {
      'Dan Abramov': 'you are awesome',
      id: 1,
    },
    {
      'Ben Ilegbodu': 'Nailed it',
      id: 2,
    },
  ],
};

In ES5 to get name and age you would do something like this

let myName = me.name;
let age = me.age;

We can minimize the code using destructuring

let { name: myName, age, ...rest } = me;

So it's a single line of code and you are telling JavaScript to get name and age from me object and alias the variable name as myName and the rest variable will carry the object without name and age. Cool huh!

Did you know that you can assign default values. Let's say a new property isEmailVerified is introduced and you may or may not get it from the api you are calling so you can do something like this

let { isEmailVerified = false } = me;

so if there is no isEmailVerified key in object it just assigns false

Dynamic key destructuring also can be done

let dynamic_key = 'social';
let { [dynamic_key]: someVar } = me;
console.log(someVar);
// <- ['twitter', 'github', 'medium']

Accessing nested properties

let {
  props: { height },
} = me;
console.log(height);
// <- 180

Top comments (0)