Javascript - Destructuring Default Values

Introduction

When using destructuring to assign a value to a variable using an object that does not have the corresponding property name, its value is set to undefined. For example:

var item = { 
        name: "Tom", 
        quantity: 5 
}; 
var { name, quantity, value } = item; 
console.log(name);           // "Tom" 
console.log(quantity);       // 5 
console.log(value);          // undefined 

Here, an extra variable value that does not have a corresponding property inside item is declared in the destructuring statement.

It gets set to undefined while name and quantity get their respective values from item.

You can choose to define a default value in case of the absence of the specified property.

To do so, specify a default value, like this:

var item = { 
        name: "Tom", 
        quantity: 5 
}; 

var { name = "Jack", quantity = 3, value = 25 } = item; 

console.log(name);          // "Tom" 
console.log(quantity);      // 5 
console.log(value);         // 25 

Here, the variables quantity and value are given 3 and 25 as their default values respectively.

Since there is no item.value property, the variable value uses its default value 25.

You can use default values in the long form of a destructuring assignment statement.

var { a, b, c: c = 3, d: FOO = 42 } = {a: 1, b: 2}; 
console.log( a, b, c, FOO );     // 1 2 3 42 

The variables a and b are declared and set to their corresponding property values from the object literal.

Related Topic