Destructuring

Introduction

Destructuring in JavaScript is a modern feature that allows you to extract values from arrays or properties from objects into separate variables. It makes your code cleaner, shorter, and easier to read.

Understanding Destructuring

Destructuring simplifies how you access data from complex structures. Instead of writing multiple lines to get values, you can do it in a single statement. It is commonly used with arrays and objects in JavaScript.

Array Destructuring

Array destructuring lets you assign values from an array to variables based on their position.

Example

const numbers = [10, 20, 30];
const [a, b, c] = numbers;

console.log(a);
console.log(b);
console.log(c);

You can also skip values if needed

const [first, , third] = numbers;

Object Destructuring

Object destructuring allows you to extract values using property names.

Example

const person = {
name: "Ali",
age: 22,
city: "Lahore"
};

const { name, age } = person;

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

Renaming Variables

You can assign properties to new variable names

const { name: userName } = person;

Default Values

If a value does not exist, you can set a default

const { country = "Pakistan" } = person;

Destructuring in Function Parameters

Destructuring is useful when working with functions

function display({ name, age }) {
console.log(name, age);
}

Benefits of Destructuring

Reduces code repetition
Improves readability
Makes working with arrays and objects easier
Commonly used in modern frameworks

Conclusion

Destructuring is an essential feature in JavaScript that helps developers write cleaner and more efficient code. It is widely used in modern development, especially in frameworks and API handling

Home » Advanced JavaScript > ES6+ Features > Destructuring