Article
Mon, Oct 16, 2023

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

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.
console.log(user.name);
  • 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, username);

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

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

  Back./Articles