# Destructuring in JavaScript

Destructuring in JavaScript is a powerful feature that allows you to extract values from arrays and objects quickly and easily. Instead of writing repetitive code to access individual values, destructuring lets you unpack them in a clean and readable way.

Imagine you receive a packed box with several items inside. Without destructuring, you'd reach in and pull out each item one by one, labeling each as you go:

```javascript
let box = ["laptop", "charger", "mouse"];

let item1 = box[0];
let item2 = box[1];
let item3 = box[2];
```

It works. But it's repetitive — you're writing `box[0]`, `box[1]`, `box[2]` for every single item. Now imagine doing that for an object with ten properties.

Destructuring is JavaScript's way of letting you unpack values from arrays or objects into named variables — in one clean, expressive line.

```javascript
let [laptop, charger, mouse] = box;
```

Same result. One line. No index juggling.

## 1\. What Destructuring Means

Destructuring is a syntax feature introduced in ES6. It lets you extract values from arrays or properties from objects, and assign them to variables, all in a single statement.

The word itself is descriptive, you're breaking a structure apart into its individual pieces.

Two important things to understand before diving in:

**Destructuring doesn't modify the original.** The array or object you're destructuring stays completely intact. You're just creating new variables that hold copies of the values.

**The syntax mirrors the structure.** For arrays, you use `[ ]`. For objects, you use `{ }`. The shape of the destructuring expression matches the shape of the data.

## 2\. Destructuring Arrays

Array destructuring assigns values based on position. The first variable gets the first element, the second variable gets the second, and so on.

Example :

```javascript
let colors = ["red", "green", "blue"];

// Without destructuring
let first = colors[0];
let second = colors[1];
let third = colors[2];

// With destructuring
let [first, second, third] = colors;

console.log(first);   // "red"
console.log(second);  // "green"
console.log(third);   // "blue"
```

**Skipping Elements**

You don't have to extract everything. Leave a blank slot with a comma to skip an element :

```javascript
let [,, blue] = colors;
console.log(blue);  // "blue" — skipped red and green
```

**Rest Elements**

Collect remaining elements into a new array using `...` :

```javascript
let scores = [95, 87, 76, 65, 54];

let [top, second, ...rest] = scores;

console.log(top);     // 95
console.log(second);  // 87
console.log(rest);    // [76, 65, 54]
```

**Swapping Variables**

One of the neatest tricks destructuring enables is swapping two variables without a temporary:

```javascript
let a = 1;
let b = 2;

[a, b] = [b, a];

console.log(a);  // 2
console.log(b);  // 1
```

Before ES6, you need a temp variable to do this. Now it's one line.

## 3\. Destructuring Objects

Object destructuring assigns values based on **property names**, not position. The variable name must match the property name in the object.

```javascript
let user = {
  name: "Priya",
  age: 24,
  city: "Pune"
};

// Without destructuring
let name = user.name;
let age = user.age;
let city = user.city;

// With destructuring
let { name, age, city } = user;

console.log(name);  // "Priya"
console.log(age);   // 24
console.log(city);  // "Pune"
```

The repetition of [`user.name`](http://user.name), `user.age`, [`user.city`](http://user.city) disappears entirely.

**Renaming Variables**

If you want a different variable name than the property name, use a colon:

```javascript
let { name: userName, city: location } = user;

console.log(userName);  // "Priya"
console.log(location);  // "Pune"
```

This is useful when a property name conflicts with an existing variable, or when the property name isn't descriptive enough in context.

**Nested Objects**

You can destructure nested objects in one expression:

```javascript
let order = {
  id: "ORD-421",
  product: {
    name: "Keyboard",
    price: 1299
  }
};

let { id, product: { name: productName, price } } = order;

console.log(id);           // "ORD-421"
console.log(productName);  // "Keyboard"
console.log(price);        // 1299
```

For deeply nested structures, though, keep readability in mind. One or two levels is usually fine. Beyond that, pull values out in separate steps.

## 4\. Default Values

When you destructure a value that doesn't exist in the source, you get undefined. Default values let you specify a fallback instead:

```javascript
let settings = { theme: "dark" };

let { theme, fontSize = 16, language = "en" } = settings;

console.log(theme);     // "dark"    — existed in object
console.log(fontSize);  // 16        — used default, not in object
console.log(language);  // "en"      — used default, not in object
```

This works for arrays too:

```javascript
let [x = 0, y = 0, z = 0] = [10, 20];

console.log(x);  // 10
console.log(y);  // 20
console.log(z);  // 0  — used default
```

Defaults only kick in when the value is `undefined`. If the value is `null`, `false`, or `0`, the default is *not* used.

```javascript
let { score = 100 } = { score: null };
console.log(score);  // null — not 100. null is not undefined.
```

This is a subtle but important distinction, especially when working with API responses where `null` and `undefined` mean different things.

**Defaults in Function Parameters**

Combining destructuring with defaults in function signatures is a powerful pattern for writing flexible, self-documenting functions:

```javascript
function createButton({ label = "Click me", color = "blue", size = "medium" } = {}) {
  return `<button class="${color} ${size}">${label}</button>`;
}

createButton({ label: "Submit", color: "green" });
// <button class="green medium">Submit</button>

createButton();
// <button class="blue medium">Click me</button>  — all defaults used
```

The `= {}` at the end means the function works even if called with no argument at all, the parameter defaults to an empty object, and each property defaults individually.

## 5\. Benefits of Destructuring

The concrete improvements destructuring brings to everyday code:

**Less repetition.** [`user.name`](http://user.name), [`user.email`](http://user.email), `user.role` written five times throughout a function becomes three clean variables extracted once at the top. The body of the function reads clearly without the constant `user.` prefix noise.

**Clearer function signatures.** A function that accepts `{ name, age, city }` tells you exactly what it needs. A function that accepts `userData` tells you nothing, you have to read the body to find out.

**Cleaner API response handling.** API responses are almost always objects. Destructuring them at the point of use keeps the rest of your logic clean.

**Works naturally with array methods.** When you map over an array of objects, destructuring in the callback parameter keeps things concise.

**Import statements.** Every time you write a named import in JavaScript, you're using destructuring syntax.

The module exports an object. You're destructuring exactly the pieces you need from it.

## Conclusion

Destructuring is one of those features that feels like a small convenience until you use it consistently and then going back to the old way feels genuinely uncomfortable.

The rule of thumb: any time you find yourself writing [`something.property`](http://something.property) more than twice in a short block of code, consider destructuring it at the top. Any time a function receives an object and uses three or more of its properties, destructure in the parameters.

It won't change what your code *does*. It will change how easily it *reads* and readable code is code that's easier to debug, easier to review, and easier to hand off to someone else.
