# Destructuring Arrays & Objects — JavaScript

Source: https://www.geekswithgeeks.com/en/javascript/js-destructuring

> Unpack values from arrays and objects in one line.

## Array destructuring

Positions matter — you can skip items with an empty slot, and even swap variables in one line.

```js
const [first, second, , fourth] = [10, 20, 30, 40];
console.log(first, second, fourth);  // 10 20 40

let [a, b] = [1, 2];
[a, b] = [b, a];   // swap
console.log(a, b); // 2 1
```

## Object destructuring

Names matter here, not order — and you can set a default for missing keys.

```js
const { name, age } = { name: "Ada", age: 36 };
console.log(name, age);

const { city = "Unknown" } = {};
console.log(city);  // Unknown
```

## Renaming while destructuring

`const { name: fullName } = user;` pulls `name` out into a variable called `fullName`.

**Quiz:** What does `const [a, , b] = [1, 2, 3]` set b to?

- [ ] 2
- [x] 3
- [ ] undefined

*Answer:* 3. The empty slot skips index 1, so b picks up index 2, which holds 3.
