Object Destructuring in JavaScript

Abdullah Imran
The Startup
Published in
3 min readSep 7, 2020
Photo by Emile Perron on Unsplash

Destructuring is a convenient way of extracting multiple values from data stored in objects and Arrays. ES6 introduced some significant improvements to the language, including the de-structuring of Objects and Arrays. Honestly speaking, these are my favorite edition in the JavaScript standard syntax.

Object destructuring

Object destructuring takes a similar tack as array destructuring. Suppose you have a student object with two properties: name and id. Previously in javascript, when you want to assign the variables to the properties of the student object, you need to make a variable from something that is inside of an object like this:

Here, you’ve got this pretty much repetitive code over and over again. But ES6 destructuring assignment makes it easier and single line like this:

Assignment without declaration:

A variable can be assigned its value with destructuring separate from its declaration.

Assigning to new variable names:

We can be assigned to a variable with a different name than the object property.

Default values:

It is possible to set default values when using the destructuring assignment.

Here, const creates variables, so id is undefined. But we can fix this problem using the default value.

Note: Default values in destructuring can’t working with null, false, and 0. It only works if the variables either don’t exist or their value is set to undefine.

Rest(…) operator in Object Destructuring:

The Rest properties add the rest syntax to destructuring.

I hope this lesson provides a clear understands of how Destructuring works in JavaScript. Hopefully, you learned something today. Happy Coding.

--

--