Javascript ES6 object and array destructuring 




Object Destructuring


Lets keep this object as an example.

const user = {
    name: "John",
    age: 21,
    address : {
        state: "Delhi",
        country: "India",            
    }
}



Prior to Object destructuring

const name = user.name;
const age = user.age;
const state = user.address.state;
const country = user.address.country;

console.log(`Hi I am ${name} age ${age} located at state ${state} of country ${country}`)




With object destructuring

const {name, age} = user;
const {state, country} = user.address;

console.log(`Hi I am ${name} age ${age} located at state ${state} of country ${country}`)




With object destructing , set the variable name other than the object key.

const {name: username, age} = user;

console.log(`Hi I am ${username} age ${age}`)




With object destructing , set the variable default value.
If the object does not have that information. It picks and render the default value.

const {phone = 9900889900} = user;
console.log(`Phone number is ${phone}`)






Array destructring



Older way to get the array value

const profiles = ['John', 'Ashok', 'Mani'];
console.log(`List of profiles are ${profiles[0]}, ${profiles[1]}, ${profiles[2]}`)




Using Array destructuring

const profiles = ['John', 'Ashok', 'Mani'];
const [John, Ashok, Mani] = profiles;

console.log(`List of profiles are ${John}, ${Ashok}, ${Mani}`)




Using array destructuring, can skip the index separate by comma.
Not all items require to destructuring, can get only those item we require. Also can use any variable name here ex Mani to Manikandan

const profiles = ['John', 'Ashok', 'Mani'];
const [, Ashok, Manikandan] = profiles;
console.log(`Like the profile of ${Ashok} and ${Manikandan}`)