Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to set default values when destructuring an object in JavaScript ?

  • Difficulty Level : Easy
  • Last Updated : 23 Dec, 2020

Destructuring in JavaScript: Destructuring was introduced in ECMA Script 6 version. It is a concept that is used to unpack or free values from arrays and objects into variables. The values corresponding to array elements or object properties get stored in the variables.

Example:

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

Javascript




var a, b;
[a, b] = [10, 20];
  
console.log(a);
  
console.log(b);

Output:



10
20

In Arrays: In Arrays, values of corresponding elements get stored in the variables.

Example 1: In order to give default values in arrays when applying the destructuring concept in arrays, we need to initialize values with some value. In this way the default values will be assigned to the variables. Below is the implementation via an example of this concept.

Javascript




let a, b, c ;
[a, b,c = 30] = [10, 20];
  
console.log(a);
  
console.log(b);
  
console.log(c);

Output:

10
20
30

Example 2: If any value is present for the respective variable then it will take that value or else then it will take the default variable. Below code snippet explains the behaviours in a more lucid and elaborative way. 

Javascript




let a, b, c;
[a, b,c = 30] = [10, 20, 50];
  
console.log(a);
  
console.log(b);
  
console.log(c);

Output: If we are not having ’50’ in that array then ‘c’ would have a ’30’ value.

10
20
50

In Objects: The values of corresponding properties get stored in the variables.

Example 1: The application and implementation of destructuring in objects are also the same as in arrays. Below are the two code snippets on how to use default values in objects.

Javascript




const student = {
    name: "Krishna"
}
const { name, age = 18 } = student; 
  
console.log(name);
  
console.log(age);

Output:

Krishna
18

Example 2:

Javascript




const student = {
    name: "Krishna",
    age : 21
}
const { name, age = 18 } = student; 
  
console.log(name);
  
console.log(age);

Output:

Krishna
21 



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!