Programming Work Time. Programmer Typing New Lines of HTML Code. Laptop and Hand Closeup. Working Time. Web Design Business Concept.

Destructuring Objects

Just like in destructuring arrays, we can also destructure objects. The syntax is slightly different using curly braces.

let animal = { id: 1, kind: ‘gorilla’ }; 
let id, kind; ({ id, kind } = animal);  console.log(id, kind);

The output would be 1 and ‘gorilla’.

Notice the parentheses. We did not have those in the destructuring arrays lesson. The reason we need to put it in parentheses is due to scope. Since JavaScript uses curly braces for code blocks, it gets confuses without the parentheses, because it doesn’t know whether you are destructuring or defining a code block. The parentheses clears this up.

Happy Coding!

Clay Hess

Share this post

Share on facebook
Share on google
Share on twitter
Share on linkedin
Share on pinterest
Share on print
Share on email
Skip to content