Binge On Code

Jun 20, 2023

27 readers

Destructure JavaScript Object With Defaults

You can really simplify your access to your JavaScript objects by using this simple method to destructure JavaScript object with defaults.

We will jump right into it. This tutorial is a simple, very simple guide on how you can have default values when you destructure JavaScript object.

Problem

If the user does not have a learning plan for the weekend, then we want to provide bingeoncode as their default way to learn!

Solution

So, we will have two hypothetical users’ weekend plans.

Scenario one

 

const userOneWeekendPlans = {

 cleaning: true,

 laundry: true,

 learningPlan: "youtube",

};

 

So, when we are using user one, let's see how to destructure JavaScript object and provide default:

 

const { learningPlan = "bingeoncode" } = userOneWeekendPlans;

 

Now, when we go ahead and log this:

 

console.log('learningPlan', learningPlan)

 

We should see youtube instead of bingeoncode, because the user already has a plan.

 

Scenario Two

So, how about a user with no weekend plan? Let's see how we can destructure JavaScript object default values.

 

const userTwoWeekendPlans = {

 cleaning: true,

 laundry: true,

};

 

Now, to get the learningPlan:

 

const { learningPlan = "bingeoncode" } = userTwoWeekendPlans;

 

Now, when we log this:

 

console.log("learningPlan", learningPlan);

 

We should see bingeoncode.

 

Conclusion

It is that easy to destructure JavaScript objects with default, and the same should apply when you destructure JavaScript array.

And with that, happy coding, and

God loves you!

Related Articles

Code Splitting And Lazy Loading

Code Splitting and lazy loading are basically augmentations of one another. Lazy loading builds on top of the power of code splitting.

Jun 8, 2023

Views 498

Get Index Of Item In JavaScript For Of Loop

In a few lines of code, you will see how easy it is to get an item’s index in JavaScript For Of Loop. Let’s do this!

Jun 16, 2023

Views 34

How To Provide Optional Property In JavaScript Object.

Let’s see how we can have JavaScript object optional property in a few lines of code. This can be really helpful, especially when you want to be concise as possible.

Jun 14, 2023

Views 9

Angular JavaScript React CSS Django Python React Native Next JS State Management Django Rest Framework Unity