Table of contents

Destructuring variables in javascript

Destructuring variables in javascript

For those like me, whose first language was not fortunate (or unfortunate) enough to be javascript, destructuring can take on esoteric overtones. In this post I will try to explain in a simple way the destructuring of objects in javascript. Destructuring is a process that, contrary to popular belief, is actually quite simple and, moreover, can improve code readability.

If you want to start learning Javascript from scratch I recommend the book Eloquent Javascript, here I recommend what I consider the best book to start.

Destructuring an object would mean converting the properties of a javascript object or list into variables or constants so that they can be more easily accessed. Let’s start with a fairly simple object.

No, I’m not going to use the classic example of person, book or dog; let’s use the example of account data characteristics.

Suppose we have stored an object that represents the data of a user account:

const userData = {isLoggedIn: True, profile: "Admin", email: "[email protected]"}

The above object has the isLoggedIn, profile and email properties. If we wanted to access the values, either to show some content conditionally we would have to do the following:

if(userData.isLoggedIn && userData.profile==='Admin'){
  redirectToDashboard()
}else{
  redirectToUserAccount()
}

In the previous code snippet, every time we access to some property of the object we will have to write the name of the userData object. But what if we assign the object’s properties to other constants?

const isLoggedIn = userData.isLoggedIn
const profile = userData.profile
const email = userData.email

Now we can access the constants individually without referring to the object. But, aren’t we repeating userData in each assignment?

Destructuring of an object in javascript

To destructure the object of the previous example, we can use the following syntax:

const userData = {isLoggedIn: True, profile: "Admin", email: "[email protected]"}
const {isLoggedIn, profile, email} = userData

Now instead of getting the values directly from the object we can get them from the constants and the code becomes easier to read.

if(isLoggedIn && profile==='Admin'){
  redirectToDashboard()
}else{
  redirectToUserAccount()
}

In addition to destructuring objects, JavaScript also allows you to destructure lists. Enter my entry on destructuring lists in Javascri to learn how to destructure lists in Javascript.

Eduardo Zepeda
Web developer and GNU/Linux enthusiast always learning something new. I believe in choosing the right tool for the job and that simplicity is the ultimate sophistication. I'm under the impression that being perfect is the enemy of getting things done. I also believe in the goodnesses of cryptocurrencies outside of monetary speculation.
Read more