# Destructuring & Spread/Rest

> What are destructuring, spread and rest in JavaScript, and how are they used in real code?

Canonical: https://www.internhack.in/learn/interview/javascript-interview/js-destructuring-spread
Last updated: 2026-11-28

Difficulty: Beginner

## Question

What are destructuring, spread and rest in JavaScript, and how are they used in real code?

## Answer

Destructuring unpacks values from arrays or properties from objects into variables in a single statement, such as `const { id, amount } = payment`. The `...` syntax does two opposite jobs: as spread it expands an array or object into individual elements or properties, and as rest it collects the remaining elements, properties or arguments into a new array or object. Which one it is depends on where it appears.

### Object and array destructuring

- Object destructuring matches by property name: `const { name, city } = user`. You can rename (`{ name: fullName }`), set defaults (`{ role = 'student' }`) and go nested (`{ address: { pincode } }`).
- Array destructuring matches by position: `const [first, second] = list`. You can skip items with holes (`const [, second] = list`) and swap variables without a temp: `[a, b] = [b, a]`.
- Defaults apply only when the value is `undefined`, not when it is `null`. `const { limit = 10 } = { limit: null }` gives `limit === null`.
- Destructuring `null` or `undefined` throws a TypeError, so guard with a default: `function f({ page = 1 } = {})`.

### Spread vs rest: same dots, opposite direction

|  | Spread | Rest |
| --- | --- | --- |
| Where it appears | Right side, function call args, array/object literals | Left side of destructuring, function parameters |
| What it does | Expands one iterable/object into many | Gathers many into one array/object |
| Example | `Math.max(...scores)` | `function log(level, ...msgs)` |
| Position rule | Anywhere, multiple times | Must be last, only once |

Rest parameters replace the old `arguments` object, which is array-like but not a real array and does not exist in arrow functions.

### Spread for copying and merging

`{ ...defaults, ...options }` merges objects, with later properties winning. `[...a, ...b]` concatenates arrays. This is the backbone of immutable updates in React and Redux: `setUser({ ...user, city: 'Bengaluru' })` creates a new object so React sees a changed reference.

The key limitation: spread makes a shallow copy. Nested objects are still shared, so changing `copy.address.city` changes the original too. For a true deep copy use `structuredClone(obj)`, available in all modern browsers and Node 17+. It handles Dates, Maps, Sets and cycles, but not functions or class prototypes.

### Where you see these every day

- React props: `function Card({ title, children, ...rest })` then `<div {...rest}>`.
- Hooks: `const [count, setCount] = useState(0)` is array destructuring.
- API responses: `const { data: { items = [] } = {} } = response`.
- Removing a key without mutation: `const { password, ...safeUser } = user`.
- Imports look similar (`import { useState } from 'react'`) but are module syntax, not destructuring; you cannot use defaults or nesting there.

**Spread makes a shallow copy. Compare spread with = and structuredClone under Tweak.**

1. **{ ...user } creates a new object**: Top-level properties are copied.
2. **Nested objects are shared**: copy.address is the same object as user.address.
3. **Mutating a nested property leaks**: copy.address.city = "Pune" changes user.address.city too.
4. **Top-level writes don't**: copy.name = "Bo" leaves user.name alone.

## Code examples

### Destructuring with rename, defaults and nesting

```
const payment = {
  id: 'pay_29QQoUBi66xm2f',
  amount: 50000,
  method: 'upi',
  customer: { name: 'Ananya', contact: { city: 'Pune' } },
  notes: null,
};

const {
  id: paymentId,
  currency = 'INR',
  customer: { name, contact: { city } },
  notes = 'none',
} = payment;

console.log(paymentId, currency, name, city, notes);

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

currency gets its default because it is undefined, but notes stays null because defaults only apply to undefined. Array destructuring swaps without a temp variable.

### Rest parameters and removing keys

```
function logEvent(level, ...messages) {
  console.log(`[${level}]`, messages.join(' | '));
}
logEvent('INFO', 'order placed', 'id=101', 'city=Delhi');

const user = { id: 7, email: 'a@b.com', password: 'hash', role: 'admin' };
const { password, ...safeUser } = user;
console.log(safeUser);
```

Rest collects leftover arguments into a real array, and object rest is a clean way to drop a field before sending a response.

### Spread is shallow; structuredClone is deep

```
const original = { name: 'Rohan', address: { city: 'Mumbai' } };

const shallow = { ...original };
shallow.address.city = 'Chennai';
console.log(original.address.city); // changed!

const deep = structuredClone(original);
deep.address.city = 'Kolkata';
console.log(original.address.city); // unchanged

const merged = { ...{ theme: 'light', lang: 'en' }, ...{ theme: 'dark' } };
console.log(merged);
```

Spread copies only the top level, so nested objects are shared. structuredClone copies the whole tree. When merging, later keys win.

## Key points

- Object destructuring matches by name, array destructuring by position
- Defaults apply only for undefined, not null
- Spread expands, rest collects; rest must be last
- Spread copies are shallow; use structuredClone for deep copies
- Default the whole parameter (= {}) to avoid destructuring undefined

## Common follow-up questions

- What is the difference between rest parameters and the arguments object?
- How would you deep clone an object that contains functions?
- Why does React need a new object reference when you update state?
- What happens if you spread a string or a Map into an array?

## Interview tips

- Explain spread and rest as the same syntax doing opposite jobs depending on position
- Point out the shallow copy limitation and name structuredClone as the modern fix
- Use a React example like useState or prop forwarding; it shows practical fluency

## Concepts covered

Destructuring, Spread Syntax, Rest Parameters, Default Values, Shallow Copy

Previous: [Array Methods (map, filter, reduce)](https://www.internhack.in/learn/interview/javascript-interview/js-array-methods) · Next: [Error Handling (try/catch/finally)](https://www.internhack.in/learn/interview/javascript-interview/js-error-handling) · [All of JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)

## More JavaScript Interview questions

- [== vs === Equality Operators](https://www.internhack.in/learn/interview/javascript-interview/js-equality-operators)
- [Arrow Functions vs Regular Functions](https://www.internhack.in/learn/interview/javascript-interview/js-arrow-functions)
- [Template Literals & String Interpolation](https://www.internhack.in/learn/interview/javascript-interview/js-template-literals)
- [null vs undefined](https://www.internhack.in/learn/interview/javascript-interview/js-null-undefined)
- [JSON: parse, stringify & Common Pitfalls](https://www.internhack.in/learn/interview/javascript-interview/js-json-parse-stringify)
- [Closures & Lexical Scope](https://www.internhack.in/learn/interview/javascript-interview/js-closures-interview)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)
