Object Destructuring

Description

This allows for saving parts of arrays or objects into variables for easy usage. It helps in accessing items in arrays or objects and writing them in a short syntax.

Resource list:

I have gotten some knowledge from this article: More on object destructuring

Example 1: Extracting data from an object and assigning it to new variables

//Using ES5, it is done this way;
let person = {
    name: "Peace",
    country: "England",
    job: "Developer"
};

let name = person.name;
let country = person.country;
let job = person.job

console.log(name); //result will be; Peace
console.log(country); //result will be; England
console.log(job); //result will be; Developer

//Using Object Destructuring in ES6
let person = {
    name: "Peace",
    country: "England",
    job: "Developer"
};

let {name, country, job} = person;

console.log(name); //result will be; Peace
console.log(country); //result will be; England
console.log(job); //result will be; Developer

//Variables can be assigned to an object that hasn't been declared like this;
let {name, country, job} = {name: "Peace",country: "England", job: "Developer"};

Example 2: Declaring variables before being assigned

let person = {name: "Peace",country: "England", job: "Developer"};
let name, country, job;

{name, country, job} = person;
console.log(name); //result will be an error

//Without an initial declaration, () parenthesis is required around the assignment statement when using the object literal destructuring assignment.
//The reason for this is because the "{name, country, job}" is considered a block and not an object literal.

//To correct it, it is done this way;
let person = {name: "Peace",country: "England", job: "Developer"};
let name, country, job;

({name, country, job} = person);
console.log(name); //result will be; Peace

//Note that when using this syntax, the () should be preceded by a semi-colon or it might execute a function from the previous line.