Destructuring assignment in JavaScript


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

Syntax

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]

Object destructuring in JS

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

Array destructuring in JS

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];

Destructuring function parameters in JS

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
Tag Template literals (Strings) in JavaScript
Difference between null and undefined in JavaScript
localStorage, sessionStorage and cookies in JavaScript?
How to play multiple video in loop using HTML5 and JavaScript