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