Add default values to variables destructured from a JavaScript object

Tomasz Łakomy
InstructorTomasz Łakomy

Share this video with your friends

Send Tweet

In this lesson we are going to learn how to set default values to variables destructured from a JavaScript object, which may come in handy if we'd like to avoid setting those variables to undefined because a certain field is not specified in the object we are destructuring from.

Instructor: [00:00] We start with an object which describes a rectangle. A rectangle has two sides, side A and side B, and we also give it a color. We then calculate the area of this rectangle. To do that, create a new function which is called calculate area. It's going to take the rectangle as an argument.

[00:16] Here I'm going to destructure side A and side B from this rectangle object and I'm going to return side A multiplied by side B. I'm going to console log and get to the console like this. Calculate area and I'm going to pass in my original rectangle object to this function.

[00:34] Let's see the result, and we have the result which is equal to 100. Let's see what happens if I'm going to remove one of those sides of this rectangle. Right now, the result is not a number because here we are destructuring this rectangle object and side A is going to be equal to 10, but side B is not defined in this object and is going to be equal to undefined.

[00:55] In this case we are multiplying undefined by 10 and the result is of course not a number. Luckily, we can give those side A and side B variables destructured from this rectangle object default values so that whenever each one of those is not provided, the function is going to provide zero instead of not a number.

[01:13] To do that, set the default value of side A like this. We're going to do exactly the same for side B. Now we have the desired effect, that side B is going to take the default value of zero unless any other value was provided.

[01:26] If I define side B again to be equal to 50, I'm going to get the proper result. Those default values are only taken into account whenever side A or side B is undefined inside of the rectangle object.