Destructuring (Arrays and Objects)

Learn about JavaScript destructuring with arrays and objects. Learn how to extract values easily and write cleaner, more readable code.

Loading...
Destructuring (Arrays and Objects)

Destructuring is a way to extract specific properties from arrays and objects and assign them to variables.

It helps you write cleaner, shorter, and more readable code.

Destructuring Arrays

Instead of:

const colors = ["red", "green", "blue"];
const color1 = colors[0];
const color2 = colors[1];
console.log(color1); // Output: red
console.log(color2); // Output: green

You can write:

const colors = ["red", "green", "blue"];
const [color1, color2] = colors;
console.log(color1); // Output: red
console.log(color2); // Output: green

You can also skip items like this:

const colors = ["red", "green", "blue"];
const [, , color3] = colors;
console.log(color3); // Output: blue

You can also assign default values to the variables like this:

const [color1, color2 = "black"] = ["red"];
console.log(color1); // Output: red
console.log(color2); // Output: black

You can access specific index positions by using bracket notation in object-style destructuring:

const colors = ["red", "green", "blue", "black"];
let { [0]: color1, [1]: color2 } = colors;
 
console.log(color1); // Output: red
console.log(color2); // Output: green

You can use the rest property (...) to gather remaining items:

const colors = ["red", "green", "blue", "black", "orange", "purple"];
const [color1, color2, ...rest] = colors;
 
console.log(color1); // Output: red
console.log(color2); // Output: green
console.log(rest); // Output: ["blue", "black", "orange", "purple"]

You can also swap values using destructuring:

let x = 5;
let y = 10;
 
[x, y] = [y, x];
 
console.log(x); // Output: 10
console.log(y); // Output: 5

Destructuring Objects

Instead of:

const admin = { name: "Shefali", age: 26 };
const name = admin.name;
const age = admin.age;
 
console.log(name); // Output: Shefali
console.log(age); // Output: 26

You can write:

const admin = { name: "Shefali", age: 26 };
const { name, age } = admin;
console.log(name); // Output: Shefali
console.log(age); // Output: 26

You can also rename variables like this:

const admin = { name: "Shefali", age: 26 };
const { name: userName } = admin;
console.log(userName); // Output: Shefali

You can also set default values like this:

const admin = { name: "Shefali", age: 26 };
 
// 'country' doesn't exist in the object, so default value is used
const { country = "India" } = admin;
console.log(country); // Output: India

Nested Arrays Destructuring

const [a, [b, c]] = [1, [2, 3]];
console.log(b); // Output: 2

Nested Objects Destructuring

const admin = { name: "Shefali", social: { X: "@Shefali__J" } };
const {
  social: { X },
} = admin;
console.log(X); // Output: "@Shefali__J"

Support my work!