The destructuring assignment is a JavaScript expression that makes easier way to unpack values from arrays or objects into variables.
The REST parameters can be destructed, that means their data can be unpacked into distinct variables
let a, b, other; [a, b,...other] = [5, 7,8,10]; console.log(a); //output: 5 console.log(b); //output: 7 console.log(other); //output: Array [8,10]
const person = { name:'harsh', age:20, address:{ city:'Delhi' } }; const {name:Fullname,age}=person; console.log(Fullname,age,person.address.city); //output :: harsh 20 Delhi
const friends =['ashish','avanish','praddep','harsh','vishal']; const [ashish,avanish,praddep,harsh,vishal,vipin]=friends; console.log(ashish,avanish,praddep,harsh,vishal,vipin); //output : ashish avanish praddep harsh vishal undefined //OR as per index basis const ashish=friends[0]; const avanish=friends[1]; const praddep=friends[2]; const harsh=friends[3]; const vishal=friends[4];
const person = { name:'harsh', age:20, address:{ city:'Delhi' } }; function printPersonInfo(info){ console.log(info.name); } printPersonInfo(person); //output : harsh //OR function printPersonInfo({name}){
console.log(name);
}
printPersonInfo(person); //output: harsh
function sum(...[a,b,c]) { return a+b+c; } sum(1); //Output : NaN sum(1,2,3); //Output : 6 sum(1,2,3,4); //Output : 6 // fourth parameter is not destructed
function sum(...argslist) { return argslist.reduce((prev,current)=>{ return prev+current; }); } sum(1); //Output : 1 sum(1,2,3); //Output : 6
Related
String Concatenation in JavaScript