Wednesday, July 3, 2024
HomeLanguagesJavascriptHow to set default values when destructuring an object in JavaScript ?

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

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: This example shows the basic example of destructuring in Javascript.

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 behaviors 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: The application and implementation of destructuring in objects are also the same as in arrays

Javascript




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


Output:

Krishna
21 

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments