To avoid the risk of Undefined there is something cool feature i.e we can assign a default value. It's useful for the case where the pulled property evaluates to undefined
let gadgets ={mobile:'๐ฑ', monitor:'๐ฅ', laptop:'๐ป', printer:'๐จ'};
console.log(`Developer Name is ${result.name} and he is from ${result.india}`);
Swapping variables without using any third variable#
// Traditional technique
functioncompute(){
let valueA =500;
let valueB =200;
let temp;
if(valueA > valueB){
temp = valueA;
valueA = valueB;
valueB = temp;
}
console.log(valueA);// 200
console.log(valueB);// 500
}
compute();
// Smart way with Destructing
functioncompute(){
let valueA =500;
let valueB =200;
[valueA, valueB]=[valueB, valueA];
console.log(valueA);// 200
console.log(valueB);// 500
}
compute();
๐ you can see a drastic amount of logic and number of lines is being reduced
Destructing import statement Even though import statements donโt follow destructuring rules, they behave a bit similarly. Whenever youโre writing module import statements, you can pull just what you need from a moduleโs public API
import{pureComponent, component}from react;
import statements have different syntax. When compared against destructuring, none of the following import statements will work
Use defaults values such as import {pureComponent = component} from react
Deep destructuring style like import {component: { someOtherComponent }} from react is not possible
Aliasing syntax import {pureComponent = component} from react :::
Spread syntax (...) is another helpful addition to JavaScript for working with arrays, objects, and function calls.
The spread allows objects and iterables (such as arrays) to be unpacked, or expanded, which can be used to make shallow copies of data structures to increase the ease of data manipulation
In the above example, I tried to add smart-watch into existing gadget object but guess what it overwrites with the new value and we lost the original content
To achieve our result we can spread the inner object as well
Rest syntax can be used as the only parameter or as the last parameter in the list. If used as the only parameter, it will gather all arguments, but if it's at the end of a list, it will gather every argument that is remaining.
functiongadgets(mobile, monitor,...args){
console.log(args);// ["๐ป", "๐จ"]
console.log(mobile);// ๐ฑ
console.log(monitor);// ๐ฅ
}
gadgets('๐ฑ','๐ฅ','๐ป','๐จ');
One can't use rest in between parameter which will throw an exception
functiongadgets(...args, mobile){
console.log(args);// SyntaxError: Rest parameter must be last formal parameter
}
gadgets("๐ฑ","๐ฅ","๐ป","๐จ");
Older code, the arguments variable could be used to gather all the arguments passed through to which is not possible now with rest