# Destructuring in JavaScript

Picture this. You get back a user object from an API. It has a name, an email, an age, a city, a subscription plan. You need to use four of those five values across the next twenty lines of code.

So you write this:

```javascript
const user = {
  name: "Priya",
  email: "priya@example.com",
  age: 28,
  city: "Pune",
  plan: "premium"
};

console.log(user.name);
console.log(user.email);
console.log(user.age);
console.log(user.city);
```

It works. But `user.` appears everywhere.

Destructuring is JavaScript's way of saying: pull out what you need, give it a name, and work with it directly.

## What destructuring means

Destructuring is a syntax for unpacking values from arrays or properties from objects into individual variables. In one line, you extract multiple values and name them. After that line, you work with plain variables no more reaching back into the original structure every time.

It doesn't modify the original object or array. It just creates new variables that hold copies of the values.

## Destructuring objects

The syntax uses curly braces on the left side of an assignment. The variable names inside the braces must match the property names in the object.

```javascript
const user = {
  name: "Priya",
  email: "priya@example.com",
  age: 28,
  city: "Pune"
};

const { name, email, age } = user;

console.log(name);  // "Priya"
console.log(email); // "priya@example.com"
console.log(age);   // 28
```

One line. Three variables. You've extracted exactly what you need and nothing more. After that line, you just use `name`, `email`, `age` clean, direct, no repeated `user.` prefix.

Here's what's actually happening each variable on the left matches a key in the object, and gets assigned that key's value:

![](https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/9c0aeffa-61ac-40be-b7b3-6be75c323edf.png align="center")

### Renaming while destructuring

What if a property name is too generic, or clashes with another variable in your scope? You can rename on the fly using a colon:

```javascript
const { name: userName, city: userCity } = user;

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

Read the colon as "rename to". The left side is the key to look for in the object. The right side is the variable name you want locally.

## Destructuring arrays

Array destructuring uses square brackets instead of curly braces. Here, order matters variables are assigned based on their position in the array, not by name.

```javascript
const scores = [95, 82, 77, 68, 55];

const [first, second, third] = scores;

console.log(first);  // 95
console.log(second); // 82
console.log(third);  // 77
```

The first variable gets index 0, the second gets index 1, and so on. The rest of the array is simply ignored.

Need to skip a position? Leave a hole with a comma:

```javascript
const [top, , bronze] = scores;

console.log(top);    // 95
console.log(bronze); // 77
```

The empty slot between the two commas skips index 1 entirely. You're essentially saying: "I want position 0 and position 2, nothing else."

Here's the positional mapping laid out:

![](https://cdn.hashnode.com/uploads/covers/6950d1ca85602739c40abd67/5cc5b54e-389b-46f4-9b05-c68c951c5e88.png align="center")

### The swap trick

One of the most satisfying uses of array destructuring is swapping two variables without a temporary holder:

```javascript
let a = 10;
let b = 20;

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

console.log(a); // 20
console.log(b); // 10
```

Before destructuring, swapping required three lines and a `temp` variable. Now it's one line and reads almost like plain English.

## Default values

What happens when you destructure a property that doesn't exist? You get `undefined`. Default values let you specify a fallback instead.

**In object destructuring:**

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

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

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

The default only kicks in when the value is `undefined`. If the property exists but is set to `null` or `0` or `""`, the default is ignored — those are real values.

### In array destructuring:

```javascript
const colors = ["red"];

const [primary = "blue", secondary = "gray"] = colors;

console.log(primary);   // "red"  — came from array
console.log(secondary); // "gray" — default, array only had one item
```

This is especially useful when writing functions that accept optional configuration you give sensible defaults right at the destructuring line instead of writing a wall of `if` checks inside the function body.

## Destructuring in function parameters

This is where destructuring really starts to clean up real code. Instead of receiving an object and then reaching into it, you destructure it directly in the parameter list:

```javascript
function renderProfile(user) {
  return `${user.name}, ${user.age} — ${user.city}`;
}

function renderProfile({ name, age, city }) {
  return `${name}, ${age} — ${city}`;
}

renderProfile({ name: "Rohan", age: 24, city: "Delhi" });
```

The second version is self-documenting. Anyone reading the function signature immediately knows what properties it expects. You don't have to read the function body to understand what shape the argument needs to have.

Add defaults to parameter destructuring and you get optional configurations for free:

```javascript
function createButton({ label, color = "blue", size = "md", disabled = false }) {
  return `<button class="${color} ${size}" ${disabled ? "disabled" : ""}>${label}</button>`;
}

createButton({ label: "Submit" });


createButton({ label: "Delete", color: "red", disabled: true });
```

Destructuring is JavaScript telling you: *stop reaching into the same container over and over. Take what you need, name it, and work with it.*

Arrays give you positional unpacking. Objects give you name-based unpacking. Both support default values, renaming, and nesting. And when you combine destructuring with function parameters, your code stops describing *how* it gets its data and starts describing *what* it does with it.

Every time you find yourself writing [`something.property`](http://something.property) three times in a row that's your cue to destructure.
