const book ={title:'Ego is the Enemy',author:'Ryan Holiday',publisher:{name:'Penguin',type:'private'}};const{title: bookName ='Ego', author,name:{publisher:{ name }}= book,type:{publisher:{ type }}= book }= book;
const user ={id:42,isVerified:true}// grabs the property by name in the object, ignores the orderconst{ isVerified, id }= user;console.log(isVerified);// > true
ObjectDestructuring=>//The destructuring assignment syntax is a JavaScript expression that makes it
possible to unpack values from arrays,
or properties from objects, into distinct variables.//example:const user ={id:42,is_verified:true};const{id, is_verified}= user;console.log(id);// 42console.log(is_verified);// true
const obj ={name:"Fred",age:42,id:1}//simple destructuringconst{ name }= obj;console.log("name", name);//assigning multiple variables at one timeconst{ age, id }= obj;console.log("age", age);console.log("id", id);//using different names for the propertiesconst{name: personName }= obj;console.log("personName", personName);Run code snippet
const person ={name:'John',age:34,hobbies:{read:true,playGames:true}}let{name,hobbies:{read, playGames}}= person;console.log(person);console.log(name);console.log(read,playGames);
/*
* On the left-hand side, you decide which values to unpack from the right-hand
* side source variable.
*
* This was introduced in ES6
*/const x =[1,2,3,4,5]const[a, b]= x
console.log(a)// prints out: 1console.log(b)// prints out: 2
// Taken from top stack overflow answerconst{ dogName ='snickers'}={dogName:undefined}console.log(dogName)// what will it be? 'snickers'!const{ dogName ='snickers'}={dogName:null}console.log(dogName)// what will it be? null!const{ dogName ='snickers'}={dogName:false}console.log(dogName)// what will it be? false!const{ dogName ='snickers'}={dogName:0}console.log(dogName)// what will it be? 0!
// Noob [ not good ]functiongetFullName(userObj){const firstName = userObj.firstName;const lastName = userObj.lastName;return`${firstName}${lastName}`;}// master [ yap little bit ]functiongetFullName(userObj){const{ firstName, lastName }= userObj;return`${firstName}${lastName}`;}// hacker [ i prefer this way ]functiongetFullName({ firstName, lastName }){return`${firstName}${lastName}`;}// example func callgetFullName({firstName:'John',lastName:'Duo'});
// In this syntax:let{property1: variable1,property2: variable2 }= object;// The identifier before the colon (:) is the property of the object and the identifier after the colon is the variable.