HomeJAVASCRIPTWhat is destructuring?

What is destructuring?

In JavaScript, destructuring is a convenient way to extract values from arrays or objects and assign them to variables in a single, short syntax.

It makes code cleaner and easier to read compared to accessing values manually.


1. Array Destructuring

You can unpack values from an array directly into variables:

const numbers = [10, 20, 30];

// Traditional way
let a = numbers[0];
let b = numbers[1];

// With destructuring
let [x, y] = numbers;

console.log(x); // 10
console.log(y); // 20

👉 You can also skip elements:

let [first, , third] = numbers;
console.log(first, third); // 10 30

👉 You can use default values:

let [p, q, r = 100] = [1, 2];
console.log(r); // 100

2. Object Destructuring

You can extract values from objects by matching keys:

const person = { name: "John", age: 25 };

// Traditional way
let name1 = person.name;
let age1 = person.age;

// With destructuring
let { name, age } = person;

console.log(name); // John
console.log(age);  // 25

👉 Renaming variables:

let { name: userName, age: userAge } = person;
console.log(userName, userAge); // John 25

👉 Default values:

let { gender = "Male" } = person;
console.log(gender); // Male

3. Nested Destructuring

You can unpack nested objects/arrays:

const user = {
  id: 1,
  profile: {
    firstName: "Alice",
    lastName: "Smith"
  }
};

let { profile: { firstName } } = user;
console.log(firstName); // Alice

4. Function Parameters Destructuring

Useful when working with objects in function arguments:

function printUser({ name, age }) {
  console.log(`${name} is ${age} years old`);
}

printUser({ name: "John", age: 25 });

✅ In short: Destructuring allows you to unpack values from arrays or objects into separate variables with a clean, concise syntax.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *