SyntaxPilot
Courses/JavaScript/Lesson 12

JavaScript · Lesson 12 of 40 · 12 min

Destructuring, spread and rest

queued

These are the notes for JavaScript episode 12. You will learn why reading fields one by one gets messy, object destructuring (renaming, default values, missing fields), destructuring function parameters and nested objects, TypeError: Cannot destructure property ... of 'undefined', array destructuring and swapping, why = doesn't copy an array (references), the spread syntax for arrays, function calls and objects, shallow vs deep copies and structuredClone, rest parameters and rest in destructuring, SyntaxError: Rest parameter must be last formal parameter, and a mini project: updating an order without changing the original. Every example runs as-is in the SyntaxPilot compiler (language: JavaScript, Node.js).

The problem: one line per field

Ravi's order object has five fields. To print the bill, we pull each field into its own variable:

const order = { customer: "Asha", item: "chai", qty: 3, price: 10, table: 4 };
const customer = order.customer;
const item = order.item;
const qty = order.qty;
const price = order.price;
console.log(`${customer}: ${qty} x ${item} = Rs ${qty * price}`);
Asha: 3 x chai = Rs 30

Four lines and four order.s to unpack one object. A second order arrives and we do the same again:

const order2 = { customer: "Meena", item: "samosa", qty: 2, price: 12 };
const customer = order2.customer;
SyntaxError: Identifier 'customer' has already been declared

A SyntaxError is found before anything runs, so nothing runs at all, not even the first bill. Why it failed: unpacking field by field is slow to write and fills the scope with names that collide. We need to unpack an object in one line.

Object destructuring: opening a tiffin box

A tiffin box In JavaScript Name
Open it once and take out roti, dal, rice const { customer, item } = order; destructuring (by name)
Put something under a new label { customer: name } renaming
Nothing sweet today? Take a backup biscuit { tip = 0 } default value
const order = { customer: "Asha", item: "chai", qty: 3, price: 10, table: 4 };
const { customer, item, qty, price } = order;
console.log(`${customer}: ${qty} x ${item} = Rs ${qty * price}`);
const { customer: name, tip = 0, note } = order;
console.log(name, tip, note);
Asha: 3 x chai = Rs 30
Asha 0 undefined
  • Curly brackets on the left of = list the fields you want; each becomes a variable with the same name. You don't have to take every field (table was skipped).
  • customer: name reads customer and stores it in a variable called name.
  • tip = 0 is used only when the field is missing (or undefined).
  • Asking for a field that doesn't exist (note) gives undefined, not an error.

Destructuring parameters and nested objects

function printOrder({ customer, item, qty = 1 }) {
  console.log(`${customer} wants ${qty} ${item}`);
}
printOrder({ customer: "Meena", item: "samosa", qty: 2 });
printOrder({ customer: "Ravi", item: "chai" });
const order = { customer: "Asha", address: { city: "Pune", pin: 411001 } };
const { address: { city } } = order;
console.log(city);
printOrder();
Meena wants 2 samosa
Ravi wants 1 chai
Pune
TypeError: Cannot destructure property 'customer' of 'undefined' as it is undefined.
  • Destructuring in the parameter list gives you named options: callers pass an object, in any order, and skip what they don't need. Many libraries work this way.
  • { address: { city } } reaches inside a nested object. (Only city becomes a variable here, not address.)
  • Calling printOrder() with nothing: there's no object to open, so it throws. Fix: give the whole parameter a default, function printOrder({ customer, item, qty = 1 } = {}). Then the call prints undefined wants 1 undefined instead of crashing.

Array destructuring and swapping

const winners = ["Asha", "Meena", "Ravi", "Kiran"];
const [first, second] = winners;
console.log(first, second);
const [, , third] = winners;
console.log(third);
let morning = "Asha";
let evening = "Ravi";
[morning, evening] = [evening, morning];
console.log(morning, evening);
Asha Meena
Ravi
Ravi Asha
  • Arrays unpack with square brackets, by position.
  • Empty commas skip positions.
  • [a, b] = [b, a] swaps two variables in one line, with no temporary variable.

Objects unpack by name, arrays unpack by position.

The shared-array bug

Ravi wants a Diwali menu: the regular menu plus jalebi.

const menu = ["chai", "samosa"];
const festivalMenu = menu;
festivalMenu.push("jalebi");
console.log("festival:", festivalMenu);
console.log("regular:", menu);
festival: [ 'chai', 'samosa', 'jalebi' ]
regular: [ 'chai', 'samosa', 'jalebi' ]

Both menus changed. A variable holds a reference to an array or object, like an address (episode 8). = copied the address, so there is one array with two names. (const doesn't help: it stops you reassigning the name, not changing the array.)

Spread: pouring out a packet

A packet of chips In JavaScript
Tear it and pour into a new bowl; the packet is untouched [...menu]: a new array with the same items
Pour two packets into one bowl, add some of your own [...menu, ...snacks, "jalebi"]
Hand the chips out one by one, not the whole packet Math.max(...prices): items as separate arguments
const menu = ["chai", "samosa"];
const festivalMenu = [...menu, "jalebi"];
console.log("festival:", festivalMenu);
console.log("regular:", menu);
const snacks = ["vada pav", "poha"];
const all = [...menu, ...snacks];
console.log(all);
const prices = [30, 160, 60];
console.log(Math.max(prices));
console.log(Math.max(...prices));
festival: [ 'chai', 'samosa', 'jalebi' ]
regular: [ 'chai', 'samosa' ]
[ 'chai', 'samosa', 'vada pav', 'poha' ]
NaN
160
  • ...menu spreads the items out. Inside new [ ], that makes a real copy.
  • Math.max wants separate numbers; given one array it returns NaN. Spread passes the items as separate arguments.

Object spread: defaults and overrides

const defaults = { sugar: "normal", size: "small", hot: true };
const myChai = { ...defaults, size: "large" };
console.log(myChai);
console.log(defaults);
const later = { size: "large", ...defaults };
console.log(later);
{ sugar: 'normal', size: 'large', hot: true }
{ sugar: 'normal', size: 'small', hot: true }
{ size: 'small', sugar: 'normal', hot: true }

When two keys clash, the one written later wins. Spread the defaults first and your changes after.

Shallow vs deep copy

const shop = { name: "Ravi's", address: { city: "Pune" } };
const copy = { ...shop };
copy.name = "Copy";
copy.address.city = "Mumbai";
console.log(shop);
const deep = structuredClone(shop);
deep.address.city = "Delhi";
console.log(shop.address.city, deep.address.city);
{ name: "Ravi's", address: { city: 'Mumbai' } }
Mumbai Delhi
  • Spread copies only the top level: a shallow copy. The nested address object is still shared, so changing copy.address.city changed the original.
  • structuredClone(value) makes a deep copy: everything, all the way down.
  • Use spread for flat objects and arrays; use structuredClone when there are objects inside objects.

Rest: gathering the rest

The same three dots do the opposite job depending on where they are:

Where the ... is Job Example
in a function call, or inside [ ] / { } you're building spread: opens up (array → items) Math.max(...prices)
in a function's parameters, or on the left of destructuring rest: gathers (items → array/object) function total(...prices)
function total(...prices) {
  console.log(prices);
  return prices.reduce((sum, p) => sum + p, 0);
}
console.log(total(10, 20));
console.log(total(30, 160, 60, 250));
console.log(total());
function bill(customer, ...items) {
  return `${customer}: ${items.join(", ")}`;
}
console.log(bill("Asha", "chai", "samosa", "jalebi"));
const { customer, ...rest } = { customer: "Meena", item: "chai", qty: 2 };
console.log(customer, rest);
[ 10, 20 ]
30
[ 30, 160, 60, 250 ]
500
[]
0
Asha: chai, samosa, jalebi
Meena { item: 'chai', qty: 2 }
  • A rest parameter collects any number of arguments into a real array (empty if there are none), so total works with 0, 2 or 4 prices. (reduce with a start value, episode 11, handles the empty case.)
  • Fixed parameters come first; the rest gathers whatever is left.
  • In destructuring, ...rest collects the remaining fields into a new object.

Rest must be last

function bill(...items, customer) {
  return customer;
}
SyntaxError: Rest parameter must be last formal parameter

The rest takes everything that's left, so nothing can come after it.

Common mistakes (and what really happens)

You wrote What happens Why Fix
const customer = ...; twice SyntaxError: Identifier 'customer' has already been declared the same name twice in one scope destructure with a rename: { customer: name2 }
function f({ a }) {} then f() TypeError: Cannot destructure property 'a' of 'undefined' as it is undefined. no object passed f({ a } = {})
const copy = menu; copy.push(x); (no error) the original changes = copies the reference [...menu]
{ ...shop } then copy.address.city = ... (no error) the original changes spread is shallow structuredClone(shop)
Math.max(prices) (no error) NaN one array, not separate numbers Math.max(...prices)
{ size: "large", ...defaults } (no error) size is small later keys win spread defaults first
function f(...items, customer) SyntaxError: Rest parameter must be last formal parameter rest takes everything left f(customer, ...items)

Mini project: update an order without changing the original

function updateOrder(order, changes) {
  return { ...order, ...changes, updatedAt: "10:30" };
}
function addItems(order, ...newItems) {
  return { ...order, items: [...order.items, ...newItems] };
}
const original = { id: 7, customer: "Asha", items: ["chai"], status: "new" };
const ready = updateOrder(original, { status: "ready" });
const bigger = addItems(ready, "samosa", "jalebi");
const { customer, items, status } = bigger;
console.log(`${customer} | ${status} | ${items.join(", ")}`);
console.log("original:", original.status, original.items);
Asha | ready | chai, samosa, jalebi
original: new [ 'chai' ]
  • updateOrder copies the order, then the changes (later keys win), then a timestamp.
  • addItems gathers any number of new items with rest, and builds a new items array with spread (a new array, so the original's items isn't shared).
  • Every step returns a new object: an immutable update. You can always compare, go back or undo. React apps update their state this way.

Try writing removeItem with filter.

Practice

  1. Write minMax(...nums) that returns [min, max], and destructure the result.
  2. Merge two settings objects so the user's choices win.
  3. Swap the first and last items of an array with destructuring.
  4. Write removeItem(order, item) without changing the original order.
Solutions and hints
function minMax(...nums) {
  return [Math.min(...nums), Math.max(...nums)];
}
const [low, high] = minMax(30, 160, 60, 250);
console.log(low, high);
const defaults = { theme: "light", sound: true, size: "medium" };
const user = { theme: "dark" };
console.log({ ...defaults, ...user });
const queue = ["Asha", "Meena", "Ravi", "Kiran"];
[queue[0], queue[queue.length - 1]] = [queue[queue.length - 1], queue[0]];
console.log(queue);
function removeItem(order, item) {
  return { ...order, items: order.items.filter((i) => i !== item) };
}
const order = { id: 7, customer: "Asha", items: ["chai", "samosa", "jalebi"] };
const smaller = removeItem(order, "samosa");
console.log(smaller.items, order.items);
30 250
{ theme: 'dark', sound: true, size: 'medium' }
[ 'Kiran', 'Meena', 'Ravi', 'Asha' ]
[ 'chai', 'jalebi' ] [ 'chai', 'samosa', 'jalebi' ]
  1. Rest gathers the numbers; spread hands them to Math.min/Math.max; array destructuring unpacks the pair.
  2. User settings go after the defaults so they win.
  3. Destructuring can assign to array positions, not just variables.
  4. filter (episode 11) returns a new array, and spread copies the rest of the order.

Quick quiz

What does this print?

const a = { x: 1, y: 2 };
const b = { y: 5, ...a, z: 3 };
const { y, ...rest } = b;
console.log(y, rest.z);
  • A. 5 3
  • B. 2 3
  • C. 2 undefined
  • D. 5 undefined
Answer

B. ...a comes after y: 5, so a's y: 2 wins. y is 2, and rest is { x: 1, z: 3 }, so rest.z is 3.

Interview questions

  • What is destructuring? Show object and array destructuring.
  • How do you rename a variable and give a default value while destructuring?
  • What happens if you destructure a property that doesn't exist? What if you destructure undefined?
  • How do you swap two variables without a temporary variable?
  • Why doesn't const b = a copy an array? How do you copy it?
  • What's the difference between spread and rest? How do you tell them apart?
  • What's the difference between a shallow and a deep copy? How do you make each?
  • When two objects are spread into one and share a key, which value wins?
  • What is a rest parameter? Why must it be last?
  • Why do React and many libraries prefer immutable updates?

Glossary

Term Meaning Example
Destructuring unpacking fields or items into variables in one line const { qty } = order;
Object destructuring unpacking by property name const { customer, item } = order;
Array destructuring unpacking by position const [first, second] = winners;
Renaming storing a field under a different variable name { customer: name }
Default value used when the field is missing or undefined { tip = 0 }
Nested destructuring unpacking from an object inside an object { address: { city } }
Named options passing one object instead of many positional arguments printOrder({ customer, item })
Swap exchanging two variables' values [a, b] = [b, a]
Reference a variable's "address" of an object or array festivalMenu = menu shares one array
Spread syntax ... that opens an array/object into items/properties [...menu, "jalebi"]
Rest parameter ... in parameters that gathers arguments into an array function total(...prices)
Rest in destructuring gathers the remaining fields/items const { customer, ...rest } = order;
Shallow copy copies only the top level; nested objects are shared { ...shop }
Deep copy copies everything, all levels structuredClone(shop)
structuredClone a built-in function that deep-copies a value structuredClone(shop)
Immutable update making a new object/array instead of changing the old one { ...order, status: "ready" }
SyntaxError code that breaks the language's rules; found before anything runs Identifier 'customer' has already been declared
TypeError a value used in a way it can't be Cannot destructure property 'customer' of 'undefined'

Summary

  • Destructuring unpacks objects by name and arrays by position, in one line, with renames (a: name) and defaults (tip = 0). Destructure parameters with = {} so an empty call doesn't crash.
  • = copies a reference, not the array or object.
  • Spread ... opens things up: copy ([...arr]), merge, add, Math.max(...arr), and object defaults + overrides (later keys win). It's a shallow copy; use structuredClone for a deep one.
  • Rest ... gathers the remaining values into an array (or object), and must come last.
  • Where the dots are decides the job: in a call or a literal they spread, in parameters or destructuring they gather.

Next episode: errors and try/catch. Every red error so far stopped the whole program. What if one bad order didn't crash Ravi's entire app?