JavaScript Destructuring for Beginners

JavaScript Destructuring for Beginners

Destructuring, Nested Destructuring, Destructuring with default values

So you've started your web development journey, and despite the constant barrage of topics like Ascnc, ES6, and Promises, you're still here, but you've been avoiding a topic called "Destructuring" for a long time. Fearing that it could be the toughest of them all, as the name suggests.

At least, that's how I felt when I got into web development. So let me give you some good news, destructuring is very easy, and what's more, it will be very good to learn it as soon as possible.

What is Destructuring ?

So destructuring in its essence is accessing elements of array and properties of objects. In this post, we will see destructuring in the context of Objects.
Let's suppose we have an object testObj having properties firstName and lastName.

const testObj = { firstName: "Anurag", lastName: "Sahu" }

Now to access its property using destructuring

const { firstName, lastName } = testObj
console.log(firstName, lastName) //Anurag Sahu

Voila, now you have seen the magic of destructuring. There is no need to use Obj.property to access the object's property.

After learning this magic you go back to code and soon realize that it's of not much use because many properties are nested objects and in the end, you had to use Obj.property after all.

Nested Destructuring

What if I told you, that nested destructuring is possible. Sounds exciting right? Let's see how to do that.

const testObj = { id:1, nestedObj: { firstName:"Anurag", lastName: "Sahu" }}

Now to access nestedObj which is a property of testObj.

const { id, nestedObj: { firstName, lastName }} = testObj
console.log( firstName, lastName ) //Anurag Sahu

note - if you try to console.log the value of nestedObj it will give undefined.
So that means only the nested property is available, and not the property itself.

How to use destructuring with promise values?

Now after learning the basic Destructuring, you try to use it with values returned from promises.

const PromiseValue = new Promise((resolve, reject) 
=> setInterval(resolve( {firstName:"Anurag", lastName: "Sahu"}, 2000 )

const { firstName, lastName } = promiseValue //Give Error

Does this rule out the use of destructuring with async values? There is a workaround for it. You can give an empty object as the default value, so in case the promiseValue is not yet available the destructuring will not result in an Error.

const { firstName, lastName } = promiseValue || { }

You can even go a step further and assign default values to the destructured properties.

const { firstName="Your", lastName:"Name" } = promiseValue

Destructuring is extremely critical for code readability and should be utilized as much as possible.

Let's Recap

  • Basic Destructuring
  • Nested Destructuring
  • Destructuring and default values