Back ./es6/destructuring

Destructuring Objects In ES6

Destructuring is an ES6 expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

An illustration with objects

Have a look at the following user object.

 // a user object
 const user = {
   name : "Maye Edwin",
   username : "mayeedwin",
   verified: true,
   social : {
     twitter: "mayeedwin1",
     github: "mayeedwin",
     site: "https://nerdlyweb.web.app"
     }
  }

Normally, if you wanted to access and use any key value, below is what you'd do.

 // print - name, username, site
 console.log(`
   Name : ${user.name}
   Username : ${user.username}
   Twitter : ${user.social.twitter}
   Site: ${user.social.site}
 `) 

This kind of repetition of calling the object gets pretty unnecessary. Below is how to destructure the object.

Note : Having curly bracket on the left of the equals sign is the new destructuring syntax.

 // get name and username first
 const {name, username} = user;
        
 // get the nested social object values on user object
 const {twitter, site} = user.social;

Now we can print our values as shown below.

// printing user after destructuring
 console.log(`
   Name : ${name}
   Username : ${username}
   Twitter : ${twitter}
   Site: ${site}
 `)

Happy coding! Read more about destructuring here by Mozilla docs.

Got any question? You wanna have a chat? Hit my inbox on twitter asap 😉