Member-only story
Write Clean Code Using JavaScript Object Destructuring
Comparing traditional and ES6 destructuring to unpack values in JavaScript

In this article, I’m going to compare traditional and new methods using ES6's destructuring assignment syntax. This syntax allows you to unpack values from complex objects and arrays. This can be used to write clean code and will definitely save you some lines.
First, we will discuss object destructuring. Then we’ll move on to arrays.
“The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.” — MDN Web Docs
Object Destructuring
Let’s make an example object of a customer. The customer
object has properties like name
and nested ones like address
:
Basic variable assignment
In the traditional approach, we would use .(dot)
notation or user[key-name]
to retrieve data:
That's a two-line job, but we can do it in one as follows:
If you want to unpack the variable with a different name, that is also possible. Notice that the property name is always on the left: