Destructuring in JavaScript

Destructuring in JavaScript

Hello guys! Alvin Uchenna here again with another amazing familiar topic I want to share, "Destructuring"

What is Destructuring?

Destructuring is a short and clean syntax for unpacking properties of an object, values of an array into distinct variables.

Destructuring allows you assign the properties of an array or objects to variables using syntax that looks like an array or object literals.

Destructuring with Array

To unpack values of an array, we have two ways of doing that and we'll look at them right away. First we can go this way:

let fruits = ["Apple", "Mango", "Orange"];
let red = fruits[0]; // Apple
let yellow = fruits[1]; // Mango
let orange = fruits[2]; // Orange

Using Destructuring Method

let fruits = ["Apple", "Mango", "Orange"];

//destructuring
const ["red", "yellow", "orange"] = fruits;
//red, yellow, orange

Destructuring with Objects

Normally to access the value of object, we can do it this way:

const person = {
     firstName: "Alvin",
     lastName: "Uchenna"
};

let fName = person.firstName; // Alvin
let lName = person.lastName // Uchenna

Using destructuring method

To destructure in objects, we have to use key name when doing so. Check below

const person = {
     firstName: "Alvin",
     lastName: "Uchenna"
};

// destructuring sample
// const { key1, ...., keyn } = object;

const { firstName, lastName } = person;

So you can see how easy it is to access or unpack our array data or object data by destructuring.

Do you make use of destructuring when writing codes? Would you mind sharing how you see or view the use of destructuring?

Don't forget to share the article and leave a comment below if you have any and hey let's keep in touch via twitter @Veri5ied