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.
If the user does not have a learning plan for the weekend, then we want to provide bingeoncode as their default way to learn!
So, we will have two hypothetical users’ weekend plans.
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.
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.
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