Destructuring


What is it?

Extract values from arrays or objects into variables.


Array Destructuring

Without Destructuring

const colors = ["red", "green", "blue"];

const first = colors[0];
const second = colors[1];

With Destructuring

const colors = ["red", "green", "blue"];

const [first, second] = colors;

console.log(first);
console.log(second);

Output:

red
green

Skip Values

const colors = ["red", "green", "blue"];

const [first, , third] = colors;

console.log(third);

Output:

blue


Object Destructuring

const user = {
    name: "Jithu",
    age: 22,
    city: "Trivandrum"
};

const { name, age } = user;

console.log(name);
console.log(age);

Output:

Jithu
22


Rename Variables

const user = {
    name: "Jithu"
};

const { name: userName } = user;

console.log(userName);

Output:

Jithu