JavaScript: Destructuring assignment

Before Destructuring assignment

Object

const person = {
    name: 'Grace',
    age: 18,
};

const name = person.name;
const age = person.age;

console.log(name, age);

Screen Shot 2020-12-11 at 10.04.32.png

Array

const fruits = ['apple', 'banana', 'grape'];

const red = fruits[0];
const yellow = fruits[1];
const blue = fruits[2];

console.log(red, yellow, blue);

Screen Shot 2020-12-11 at 10.13.03.png

Destructuring assignment

Object

const person = {
    name: 'Grace',
    age: 18,
};

const { name, age } = person;

console.log(name, age);

Screen Shot 2020-12-11 at 10.07.56.png

Array

const fruits = ['apple', 'banana', 'grape'];
const [red, yellow, blue] = fruits;
console.log(red, yellow, blue);

Screen Shot 2020-12-11 at 10.14.53.png

Destructuring makes us reduce a lot of lines of code. It's much easier and simpler!

Reference: MDN