DEV Community

Jaime Panaia-Rodi
Jaime Panaia-Rodi

Posted on

Object Destructuring

While learning how to write forms in React I learned about an interesting syntax in JavaScript called destructuring. It can be used on arrays as well as objects to quickly extract elements. Here's an example:

const hero = {
   name: 'Wonder Woman',
   realName: 'Diana Prince'
};

const { name, realName } = hero;
name;     // => 'Wonder Woman',
realName; // => 'Diana Prince'
Enter fullscreen mode Exit fullscreen mode

This is so cool. Instead of having to create variables for each element inside the object like this:

const name = hero.name
const realName = hero.realName
Enter fullscreen mode Exit fullscreen mode

You can simply grab any element after writing one line of code:

const {prop1, prop2, ...} = object
Enter fullscreen mode Exit fullscreen mode

More details here from a very smart human.

Top comments (0)