Destructuring allows you to extract Array elements or object properties and store them in distinct variables. We can use destructuring with both Arrays and Objects. Let’s see some examples.
Array Destructuring
let x, y, z; [ x, y, z ] = [ 10, 20, 30 ]; console.log(x); // 10 console.log(y); // 20 console.log(z); // 30
Object Destructuring
let { x, y } = { x: 10, y: 20 }; console.log(x); // 10 console.log(y); // 20
The variable’s name inside braces on the left-hand side should match with the properties name of the assigned object else undefined
values will be assigned to the respective variable. For example:
let { x, z } = { x: 10, y: 20 }; console.log(x); // 10 console.log(z); // undefined
Here there is no property named “z” is present in the object so it is assigned with undefined
.
One more Example:
let x = 0; let { x: y } = { x: 55 }; console.log(x); // 0 console.log(y); // 55
Working with Default values
You can define default values in destructuring. If no values get assigned to the variable on the left-hand side, then the default value will remain unchanged else the assigned value will replace the default value.
Arrays Destructuring
let x, y, z; [x = 4, y = 6, z = 8] = [10, 15]; console.log(x); // 10 console.log(y); // 15 console.log(z); // 8
Object Destructuring
let {x = 4, y = 6, z = 6} = {x: 10, y: 20}; console.log(x); // 10 console.log(y); // 20 console.log(z); // 6
Skipping some values in middle in Array
If you know the exact size of the array and you want some specific index values, then you can skip some variables in the middle. See the example.
let x, y, z; [x, , y, , z] = [10, 20, 30, 40, 50]; console.log(x); // 10 console.log(y); // 30 console.log(z); // 50
Here we have skipped the 2nd and 4th indexed values.
Destructuring with Rest Parameter
If we have a rest parameter on the left-hand side array, then the extra elements of the assigned array will be assigned to the rest parameter and will store as an array.
let x, y, z; [x, y, ...z] = [10, 20, 30, 40, 50]; console.log(x); // 10 console.log(y); // 20 console.log(z); // [30, 40, 50]
Swapping variables using Destructuring
let x = 10, y = 20; [x, y] = [y, x]; console.log(x); // 20 console.log(y); // 10
Web Developer by Profession, Blogger by Passion.
JavaScript | React | Next | Angular | Vue | HTML | CSS