JS: JS Destructring: Objects, Arrays & Variables Assignment | JavaScript
JavaScript Destructring Assignment
Destructuring assignment in JavaScript allows Objects properties and Array members to be assigned to local variables at declaration time.
Modern JavaScript allows Destructuring assignments of Objects properties, Arrays elements and Variables, making the code more readable, precised and elegant.
Object Destructuring
Assignment of Object properties & members: Consider an object fruit
var fruit = {apple:'🍎', banana:'🍌', cherry:'🍒'};
Following is the traditional way of assignments of object properties to a local variable:
var apple = fruit.apple;
var banana = fruit.banana;
var cherry = fruit.cherry
console.log(apple, banana, cherry);
We can achieve properties assignment to local variables in a single line of code:
var {apple, banana, cherry} = fruit;
console.log(apple, banana, cherry);
JavaScript intelligently copies the respected properties to the declared variables var
.
Assignment with destructing is more concised, readable and elegant than traditional way.
We may also change the variable name different than the object property:
var {apple: redApple, banana, cherry} = fruit;
console.log(redApple, banana, cherry);
Simply use the original property name (apple), type colon (:) and give the new name for the identifier (redApple).
Destructuring also allows to use a property that is not a valid variable name for an identifier:
var fruit = {apple:'🍎', banana:'🍌', cherry:'🍒', 'blue-berry':'🫐'};
var {apple: redApple, banana, cherry, 'blue-berry': blueBerry} = fruit;
console.log(redApple, banana, cherry, blueBerry);
Just like using variable redApple for the property apple, we used blueBerry for 'blue-berry'.
Destructuring Nested Objects
We can extract object within an object i.e. nested objects. To have a look at following object,
var fruit = {
apple : {
seed : '';
}
};
var {apple :{seed}} = fruit;
console.log(seed);
Destructuring Objects in Loops Iteration
We can extract object within an object i.e. nested objects. To have a look at following object,
var fruits = [
{name:'Apple', color:'red', emoji: '🍎'},
{name:'Banana', color:'yellow', emoji: '🍌'},
{name: 'Cherry', color:'red', emoji: '🍒'}
];
Traditionally, we do the following to access each element in the array (imparative programming)
for (var fruit of fruits){
console.log(fruit.name, fruit.color, fruit.emoji);
}
With destructing, we can directly declare the properties of our choice in while wihile declaring the variable for iteration:
for (var {name, color, emoji} of fruits){
console.log(name, color, emoji);
}
or even the limited properties of our choice:
for (var {name, emoji} of fruits){
console.log(name, emoji);
}
Destructuring assignment in functions
We can limit the properties as arguments to pass through the function parameters:
var fruits = [
{name:'Apple', color:'red', emoji: '🍎'},
{name:'Banana', color:'yellow', emoji: '🍌'},
{name: 'Cherry', color:'red', emoji: '🍒'}
];
Instead of coding this:
function fruitName(fruit){
console.log(fruit.name);
}
for(var fruit of furits)
fruitName(fruit);
We may achieve the same, the following way:
function fruitName({name}){
console.log(name);
}
for(var fruit of furits)
fruitName(fruit);
Swap variables using Destructuring Assignment
Variable swapping requires an extra variable to make code simpler. But we can swap two variables without using the third variable.
Variable swapping with extra variable
var a = 'First';
var b = 'Second';
var temp;
console.log('Before swapping', {a,b});
//Swapping with extra variable
temp = a;
a = b;
b = temp;
console.log('After swapping', {a,b});
We can swap with a single statement with destructing assignment:
var a = 'First';
var b = 'Second';
console.log('Before swapping', {a,b});
//Swapping with Destructuring
[b, a] = [a, b];
console.log('After swapping', {a,b});
Arrays Destructuring
Assignments of array elements: We can assign array elements to declared variables:
var fruits = ['apple', 'banana', 'cherry'];
var f1 = fruits[0];
var f2 = fruits[1];
var f3 = fruits[2];
Adoprting destructing assignment, assign elements of an array in a single line of code:
var fruits = ['apple', 'banana', 'cherry'];
var [f1, f2, f3] = fruits;
console.log({f1, f2, f3});
{f1: 'apple', f2: 'banana', f3: 'cherry'}
Destructuring assigns undefined to an extra variable declared, in case elements are less:
var fruits = ['apple', 'banana', 'cherry'];
var [f1, f2, f3, f4] = fruits;
console.log({f1, f2, f3, f4});
{f1: 'apple', f2: 'banana', f3: 'cherry', f4: undefined}
JavaScript assigned undefined to the fourth variable f4 because there are only 3 elements in arr.
We may keep some elements and skip other elements:
var fruits = ['apple', 'banana', 'cherry'];
var [,, f3] = fruits;
console.log({f3});
{f3: 'cherry'}
JavaScript assigned the third element only to f3 from arr because we skipped the first two element with commas.
We may also keep some elements in variables and rest of them in an other array:
var fruits = ['apple', 'banana', 'cherry'];
var [f1, ...otherFruits] = fruits;
console.log({f1, otherFruits});
{f1: 'apple', otherFruits: ['banana', 'cherry']}
JavaScript assigned the third element only to f3 from arr because we skipped the first two element with commas.
Regular Expresion Destructuring (RegExp)
We can store Regular Expresion (RegExp) results in variables easily with Destructuring assignment:
var re = /\w+\s*/g;
var name = 'foo bar';
var [firstName, lastName] = name.match(re);
console.log({firstName, lastName});