Destructuring, spread and rest
Course contents (16 lessons)
- Modern syntax
- Destructuring, spread and rest
- ES modules: import and export
- Objects, this and errors
- Classes and prototypes
- Understanding this in JavaScript
- Error handling: try, catch and custom errors
- Asynchronous JavaScript
- The event loop: how JavaScript handles waiting
- From callbacks to promises to async/await
- Fetch and REST APIs
- Working in the browser
- Local storage and session storage
- Debugging with browser DevTools
- Performance basics: debounce and throttle
- Node.js essentials
- Node.js and npm basics
- Working with files in Node.js
- A tiny HTTP server with Node.js
- Testing and the final project
- Testing basics with the Node.js test runner
- Final project: a post explorer with modules and fetch
Three small features, used everywhere
Destructuring, spread and rest all use a few characters of syntax to remove a lot of repetitive code. If you read any modern JavaScript project, you will see them in nearly every file, so it is worth getting comfortable with them first.
Object destructuring
Without destructuring, pulling values out of an object takes one line each:
const user = { name: "Sara", age: 28, city: "Lahore" };
const name = user.name;
const age = user.age;
With destructuring you do it in one statement:
const user = {
name: "Sara",
age: 28,
address: { city: "Lahore", zip: "54000" },
};
const { name, age } = user;
console.log(name, age); // Sara 28
// rename while unpacking
const { name: fullName } = user;
console.log(fullName); // Sara
// default value if the property is undefined
const { country = "Pakistan" } = user;
console.log(country); // Pakistan
// nested
const { address: { city } } = user;
console.log(city); // Lahore
The names inside the braces must match the property names. If you want a different variable name, write property: newName. A default after = is used only when the value is undefined.
Array destructuring
For arrays, the position matters, not the name:
const colours = ["red", "green", "blue"];
const [first, second] = colours;
console.log(first, second); // red green
const [, , third] = colours; // skip with empty slots
console.log(third); // blue
// swap two variables without a temp
let a = 1, b = 2;
[a, b] = [b, a];
console.log(a, b); // 2 1
You have already seen this with Object.entries, where for (const [key, value] of ...) unpacks each pair.
Destructuring in function parameters
This is where I use it most. Instead of remembering the order of five arguments, pass one object and unpack it:
function createUser({ name, age = 18, role = "viewer" }) {
return `${name} (${age}) can act as ${role}`;
}
console.log(createUser({ name: "Ali" }));
console.log(createUser({ name: "Zara", role: "admin", age: 30 }));
Callers can pass the options in any order and skip the ones with defaults. When you see createUser({ ... }) at the call site, each value has a label. Compare that with createUser("Zara", 30, "admin"), where you must remember what each position means.
The spread operator
Three dots in front of an array or object "spreads" its contents out. Use it to copy and combine.
const evens = [2, 4, 6];
const odds = [1, 3, 5];
const all = [...odds, ...evens]; // [1, 3, 5, 2, 4, 6]
const copy = [...evens]; // independent copy
console.log(Math.max(...evens)); // 6, spread into arguments
const defaults = { theme: "light", fontSize: 14 };
const saved = { fontSize: 18 };
const settings = { ...defaults, ...saved };
console.log(settings); // { theme: 'light', fontSize: 18 }
For objects, later properties overwrite earlier ones. That gives you the "defaults plus overrides" pattern in one line.
Spread makes a shallow copy. Nested objects are still shared with the original, as we saw in the fundamentals course.
Immutable updates
Spread is the usual way to update data without changing the original, which many front-end libraries rely on:
const state = { count: 1, user: { name: "Ali" } };
const next = { ...state, count: state.count + 1 };
console.log(state.count, next.count); // 1 2
const list = [1, 2, 3];
const added = [...list, 4];
const removed = list.filter(n => n !== 2);
Rest parameters and rest in destructuring
The same three dots on the receiving side do the opposite. They collect the remaining items into an array or object.
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
const [head, ...tail] = [10, 20, 30, 40];
console.log(head, tail); // 10 [20, 30, 40]
const { password, ...safeUser } = { name: "Sara", password: "secret", role: "admin" };
console.log(safeUser); // { name: 'Sara', role: 'admin' }
The last example is a handy trick. It builds a copy of the object without the password field.
How to tell spread from rest: if the dots appear where a value is being used (in a call, in an array or object literal), it is spread. If they appear where values are being received (a parameter list or a destructuring pattern), it is rest. Rest must always come last.
Common mistakes
- **Destructuring
nullorundefined.**const { a } = undefinedthrows a TypeError. Give the source a default:const { a } = obj ?? {}. - Wrong property name. Destructuring a property that does not exist gives
undefined, with no error. Check spelling. - Expecting spread to deep copy. Nested objects are still shared.
- Putting rest in the middle.
[...a, b] = listis a syntax error. Rest goes last. - Mixing up the order for arrays. Array destructuring is by position. Object destructuring is by name.
Try it yourself
- Given
const book = { title: "Dune", author: "Herbert", year: 1965 }, extract title and year into variables. - Write a function
formatPrice({ amount, currency = "PKR" })that returns text like1500 PKR. - Merge two arrays without duplicates using
[...new Set([...a, ...b])]and explain each part. - Write
average(...numbers)that returns the mean of any number of arguments.
const user = {
name: "Sara",
age: 28,
address: { city: "Lahore", zip: "54000" },
};
const { name, age } = user;
console.log(name, age); // Sara 28
// rename while unpacking
const { name: fullName } = user;
console.log(fullName); // Sara
// default value if the property is undefined
const { country = "Pakistan" } = user;
console.log(country); // Pakistan
// nested
const { address: { city } } = user;
console.log(city); // Lahore
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account