JavaScript Destructuring and Default Values Tutorial

In this section, we will learn what the default values in destructuring are and how to use it in JavaScript.

Note: we’re assuming you’re already familiar with the object destructuring in JavaScript.

What is Default Values in JavaScript Destructuring?

When we’re destructuring an object, if the target property that we want to get its value does not exist in the object, the related variable will get the value `undefined`.

In situations like this, we can use the default value instead to change the `undefined` value to something else for that variable.

Basically, we can specify a default value that will only be applied if the property is missing or has the value `undefined`.

To specify a default value, we put an assignment operator after the variable in which we think might end up having the value `undefined` and on the right side of the `=` operator, we put the default value.

Example: using default values in JavaScript object destructuring

const obj = {
  firstName: "John",
  email: `[email protected]`
}
const{
  lastName: name = "Doe"
} = obj; 
console.log(name);

Output:

Doe

How Does Object Destructuring and Default Values Work?

Here the identifier `name` is used in the object destructuring to get the value of the `lastName` property in the `obj` object. But this object does not have such property. So the identifier `name` will end up getting the value `undefined` at first. In a situation like this, the default value will kick in and replace the value `undefined` for the identifier `name`.

That’s how when we called the `name` in the `console.log(name);` statement, the word `Doe` appeared on the console.

Example: JavaScript Arrays Destructuring and Default Values

const array = ["Omid",undefined]; 
const [firstValue = "John",secondValue = "Doe"] = array; 
console.log(firstValue, secondValue);

Output:

Omid Doe

Here, because the second element of the array is set to undefined, then the default value for the `secondValue` variable will be used instead.

Leave a Reply