# Destructuring in JavaScript

* * *

## **What is Destructuring?**

Imagine you have a gift box with many items inside. Instead of reaching into the box every time you need something, you take everything out and put it on the table neatly organized.

That is exactly what **destructuring** does in JavaScript. It lets you *pull out* values from arrays or objects and put them into separate variables — all in one clean step.

Destructuring = "unpack values into variables, quickly and neatly."

![](https://cdn.hashnode.com/uploads/covers/6950f0fdfe9a13bd8ea78167/f943d621-f5e9-4bf2-937e-ff9dfa499a27.png align="center")

* * *

## **Destructuring Arrays**

With arrays, destructuring assigns values based on their **position**. The first variable gets the first item, the second variable gets the second item, and so on.

![](https://cdn.hashnode.com/uploads/covers/6950f0fdfe9a13bd8ea78167/e18322f2-dc60-4278-9223-a392582258f3.png align="center")

The square brackets \[ \] on the left side tell JavaScript: "I want to unpack this array."

![](https://cdn.hashnode.com/uploads/covers/6950f0fdfe9a13bd8ea78167/1aadd01f-ab8c-4f96-9248-564d050ca6ce.png align="center")

You can also **skip items** using an empty comma:

```javascript
const [, second] = ["apple", "banana", "mango"]; console.log(second); // "banana" ← skipped "apple"
```

* * *

## **Destructuring Objects**

With objects, destructuring matches by **property name**, not position. The variable name must match the key in the object.

![](https://cdn.hashnode.com/uploads/covers/6950f0fdfe9a13bd8ea78167/a9a7f0ab-06d1-4dfd-b6f0-99ba2179981b.png align="center")

You can also give the variable a **different name** using a colon:

```javascript
const { name: userName } = user; console.log(userName); // "omkar" ← renamed from 'name'
```

* * *

## **Default Values**

What if a value doesn't exist in the array or object? Without a default value, you get **undefined**. With a default value, you get a safe fallback instead.

```javascript
const [a = "hello", b = "world"] = ["hi"]; console.log(a); // "hi" ← value existed, used it console.log(b); // "world" ← no value, used default
```

```javascript
const { name, role = "viewer" } = { name: "Rahul" }; console.log(name); // "Rahul" ← existed in object console.log(role); // "viewer" ← not in object, used default
```

Default values only kick in when the value is undefined. If the value is null, the default does NOT apply.

* * *

## **Benefits of Destructuring**

Destructuring is not just shorter — it makes your code much easier to read and manage.

![](https://cdn.hashnode.com/uploads/covers/6950f0fdfe9a13bd8ea78167/d7584047-840f-4a74-8dde-010ac1217faa.png align="center")
