Destructuring, spread & rest in React JS
Course: React JS Training
Topic: Destructuring, spread & rest
Course Link: React JS Training
Demo Link: Register for a Course Demo
1. Introduction: why destructuring, spread and rest matter
Modern JavaScript introduced three closely related features that changed the way developers write everyday code: destructuring, the spread operator and rest parameters. All three arrived with ES6 and later refinements, and all three are used constantly in real projects. If you open any modern React codebase, you will see them on almost every screen.
Why do they matter so much? Before these features existed, working with arrays and objects required a lot of repetitive typing. You pulled values out one by one, copied objects property by property, and collected function arguments manually. Destructuring lets you unpack values in a single line, the spread operator lets you copy and merge data cleanly, and rest parameters let a function accept any number of arguments gracefully.
For a React learner these features are not optional. React components receive their data as a single props object, and the standard modern style is to destructure that object right in the function signature. State updates in React also rely on the spread operator, because React expects you to create new arrays and objects rather than mutate existing ones. In short: you cannot read or write modern React code comfortably without these three tools.
- Destructuring unpacks values from arrays or properties from objects into separate variables.
- Spread expands an array or object into individual elements or properties, usually to copy or merge it.
- Rest collects multiple values into a single array or object, usually inside a function signature or a destructuring pattern.
Notice the symmetry: spread expands data, rest gathers data. They use the same three-dot syntax (...) but do opposite jobs depending on where they appear. This page explains each one in plain words, then shows how they work with examples that grow from very simple to realistic.
2. Destructuring in simple words
Destructuring is a shorthand for pulling values out of an array or an object and storing them in variables. Imagine a parcel delivery: instead of opening the box and taking items out one at a time, destructuring is like saying "give me the first item as a, the second as b, and the third as c" in one instruction.
Here is the old way and the new way side by side. Both do exactly the same thing:
// The old way: one line per value
const user = ["Asha", "Pune", 25];
const name = user[0];
const city = user[1];
const age = user[2];
// The modern way: one line does all three
const [userName, userCity, userAge] = ["Asha", "Pune", 25];
console.log(userName); // "Asha"
console.log(userCity); // "Pune"
console.log(userAge); // 25
The left-hand side of the = sign is a pattern that describes the shape of the data. JavaScript matches the pattern against the value on the right and assigns each piece to the matching variable. The same idea works for objects, where you match by property name instead of by position.
Destructuring does not destroy the original array or object. The word "destructuring" refers to the structure of the pattern, not to any damage to the data. The original value stays untouched.
3. Key terms you should know
These terms appear throughout this page and in almost every JavaScript article you will read, so it is worth fixing them in your mind before looking at syntax.
| Term | Plain meaning | Quick example |
| Destructuring assignment | Unpacking values from an array or object into variables using a pattern | const [a, b] = [1, 2]; |
| Pattern | The shape written on the left side that describes what to extract | { name, age } in const { name, age } = user; |
| Iterable | Any value that can be walked through item by item, such as arrays and strings | const [x, y] = "hi"; |
| Spread operator | Three dots that expand an array or object into its individual pieces | const copy = [...oldArray]; |
| Rest parameter | Three dots in a function signature or pattern that gather the remaining values | function sum(...nums) {} |
| Default value | A fallback used when the extracted value is undefined | const [a = 10] = []; |
| Mutation | Changing an existing array or object in place, which spread helps you avoid | list.push(item) mutates; [...list, item] does not |
4. Array destructuring: syntax and structure
Array destructuring uses square brackets on the left side of an assignment. The position of each variable in the pattern decides which array element it receives. Position is the only thing that matters; the names of the variables are entirely your choice.
Basic structure
const colors = ["red", "green", "blue"];
const [first, second, third] = colors;
console.log(first); // "red"
console.log(second); // "green"
console.log(third); // "blue"
Reading the pattern
Think of the pattern as a mirror of the data. If the array has three elements, a three-variable pattern captures all three. The matching happens strictly left to right:
- JavaScript evaluates the right side (the array).
- It takes element
0 and assigns it to the first variable in the pattern.
- It takes element
1 and assigns it to the second variable, and so on.
- If the pattern is longer than the array, the extra variables get
undefined.
const [a, b, c, d] = [1, 2, 3];
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
console.log(d); // undefined (nothing left to assign)
Destructuring with let and var
Although const is the usual choice, the same pattern works with let and even without any keyword when the variables already exist. When destructuring without a keyword in a statement context, wrap the whole assignment in parentheses so JavaScript does not mistake the bracket for an array literal:
let x, y;
[x, y] = [10, 20];
console.log(x, y); // 10 20
5. How array destructuring works step by step
Let us walk through one example slowly, as the JavaScript engine would process it.
const scores = [88, 74, 91];
const [maths, science, english] = scores;
- Step 1: The engine sees square brackets on the left of
=, so it recognises an array destructuring pattern with three slots: maths, science, english.
- Step 2: It evaluates the right side.
scores is an array with three elements: 88 at index 0, 74 at index 1, 91 at index 2.
- Step 3: It assigns index 0 to the first slot:
maths becomes 88.
- Step 4: It assigns index 1 to the second slot:
science becomes 74.
- Step 5: It assigns index 2 to the third slot:
english becomes 91.
- Step 6: The original
scores array is unchanged and can still be used elsewhere in the program.
A useful detail: destructuring works on any iterable, not just arrays. A string is an iterable of characters, so you can split it into variables directly:
const [h, i] = "hi";
console.log(h); // "h"
console.log(i); // "i"
You can also destructure the result of a function call directly, which is very common when a function returns several values:
function getPoint() {
return [3, 7];
}
const [x, y] = getPoint();
console.log(x, y); // 3 7
6. Skipping, defaults and swapping in array destructuring
Three small tricks make array destructuring flexible enough for daily use: skipping positions, providing defaults, and swapping variables.
Skipping elements
If you only need certain positions, leave empty slots in the pattern. A comma with nothing between the brackets means "skip this index":
const [first, , third] = ["gold", "silver", "bronze"];
console.log(first); // "gold"
console.log(third); // "bronze"
Default values
If the array is shorter than the pattern, missing positions become undefined. You can supply a fallback with = inside the pattern. The default is used only when the value is undefined, not when it is some other value such as 0 or an empty string:
const [name = "Guest", city = "Unknown"] = ["Meera"];
console.log(name); // "Meera" (real value wins)
console.log(city); // "Unknown" (fallback used)
Swapping variables without a temporary variable
Before destructuring, swapping two variables required a third "temp" variable. With destructuring, the swap is a single line:
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a); // 2
console.log(b); // 1
| Trick | Pattern | When to use it |
| Skip | const [a, , c] = arr; | You need index 0 and index 2 but not index 1 |
| Default | const [a = 0] = arr; | The array might be too short and you want a sensible fallback |
| Swap | [a, b] = [b, a]; | Exchanging two existing variables in one line |
7. Object destructuring: syntax and structure
Object destructuring uses curly braces on the left side of the assignment. Here you match by property name, not by position, which makes object destructuring more forgiving than array destructuring: order does not matter, and you can extract only the properties you care about.
Basic structure
const student = {
name: "Ravi",
course: "React JS",
marks: 82
};
const { name, course, marks } = student;
console.log(name); // "Ravi"
console.log(course); // "React JS"
console.log(marks); // 82
The variable names must match the property names exactly, because that is how JavaScript finds the values. If you write const { nam } = student; you get undefined, since there is no property called nam.
Order does not matter
const { marks, name } = student; // works fine, same result
Extracting only what you need
const { course } = student;
console.log(course); // "React JS" (name and marks are simply ignored)
Object destructuring also works with function return values. This is the everyday pattern in React when a hook returns an object:
function getUser() {
return {
id: 7,
role: "student"
};
}
const { id, role } = getUser();
console.log(id, role); // 7 "student"
8. Renaming, default values and nested destructuring
Real data rarely has the exact variable names you want, and real objects often contain other objects. Two extensions handle this: renaming with a colon, and defaults with an equals sign. Nesting combines both.
Renaming while destructuring
The syntax { property: newName } reads as "take the property called property and store it in a variable called newName":
const product = {
title: "Keyboard",
price_inr: 1450
};
const { title, price_inr: price } = product;
console.log(title); // "Keyboard"
console.log(price); // 1450
Defaults, with and without renaming
const settings = {
theme: "dark"
};
const { theme, language = "English" } = settings;
console.log(theme); // "dark"
console.log(language); // "English" (fallback, because language is missing)
You can combine renaming and a default in one pattern. The default always comes last:
const { region: country = "India" } = settings;
console.log(country); // "India"
Nested destructuring
When an object contains another object or an array, you can reach inside it directly by continuing the pattern:
const user = {
name: "Anita",
address: {
city: "Nagpur",
pin: 440001
},
tags: ["student", "react"]
};
const {
name,
address: { city, pin },
tags: [firstTag]
} = user;
console.log(name); // "Anita"
console.log(city); // "Nagpur"
console.log(pin); // 440001
console.log(firstTag); // "student"
One important detail: in the pattern address: { city, pin }, the word address is only a path, not a variable. If you also want to keep the whole address object, extract it separately:
const { address, address: { city } } = user;
console.log(address); // the full object
console.log(city); // "Nagpur"
9. Destructuring in function parameters
The single most useful place for destructuring is a function parameter list. Instead of receiving one big object and digging into it inside the body, you unpack exactly the properties you need right in the signature. This is how most modern React components are written.
The old way versus the new way
// Old style: access properties through the parameter
function greet(user) {
console.log("Hello " + user.name + " from " + user.city);
}
// Modern style: destructure in the signature
function greet({ name, city }) {
console.log("Hello " + name + " from " + city);
}
greet({ name: "Kiran", city: "Surat" }); // Hello Kiran from Surat
Defaults in parameter destructuring
Defaults work exactly as before, and they make parameters effectively optional:
function showPlan({ plan = "Free", days = 7 } = {}) {
console.log(plan + " plan for " + days + " days");
}
showPlan(); // Free plan for 7 days
showPlan({ plan: "Pro" }); // Pro plan for 7 days
showPlan({ plan: "Pro", days: 30 }); // Pro plan for 30 days
Note the extra = {} at the end. It protects the function when it is called with no argument at all: without it, destructuring undefined would throw an error.
Why React developers use this constantly
A React component is just a function that receives a props object. Destructuring in the signature makes the component's dependencies visible at a glance:
function ProfileCard({ name, role, avatarUrl }) {
// name, role and avatarUrl are ready to use here
return name + " (" + role + ")";
}
Anyone reading the signature immediately knows what data the component needs, without scanning the body.
10. The spread operator: syntax and how it works
The spread operator is three dots written before an array, object or iterable: .... Wherever you write it, JavaScript takes the contents and "spreads them out" into that place, as if you had typed each element individually.
The mental model
const fruits = ["apple", "banana"];
// These two lines are equivalent in effect:
const basket1 = ["mango", ...fruits, "grape"];
const basket2 = ["mango", "apple", "banana", "grape"];
console.log(basket1); // ["mango", "apple", "banana", "grape"]
The spread operator said: "replace me with the elements of fruits". That is the whole idea.
Where spread is allowed
- Inside an array literal, to build a new array from old ones.
- Inside an object literal, to build a new object from existing ones.
- In a function call, to pass an array as separate arguments.
Spread creates copies, not links
This is the property that makes spread essential in React. Spreading into a new literal produces a new array or object. Changing the copy does not affect the original:
const original = [1, 2, 3];
const copy = [...original];
copy.push(4);
console.log(original); // [1, 2, 3] (untouched)
console.log(copy); // [1, 2, 3, 4]
Spread is a shallow copy. Nested arrays and objects inside the copy still point to the same inner values as the original. For deeply nested data you need a deep copy technique, which is a separate topic.
11. Spread worked examples from simple to realistic
Example 1: merging arrays
const morning = ["tea", "toast"];
const evening = ["coffee", "soup"];
const meals = [...morning, ...evening];
console.log(meals); // ["tea", "toast", "coffee", "soup"]
Example 2: adding an item without mutating
const todos = ["learn HTML", "learn CSS"];
const updated = [...todos, "learn JavaScript"];
console.log(todos); // ["learn HTML", "learn CSS"]
console.log(updated); // ["learn HTML", "learn CSS", "learn JavaScript"]
Example 3: copying and merging objects
When the same key appears in a later object, the later value wins. This makes spread a clean way to apply overrides:
const defaults = { theme: "light", fontSize: 14, language: "English" };
const userChoice = { theme: "dark" };
const settings = { ...defaults, ...userChoice };
console.log(settings);
// { theme: "dark", fontSize: 14, language: "English" }
Example 4: passing an array to a function
Spread turns an array into separate arguments, which is handy for functions that expect individual values:
const marks = [78, 85, 92];
console.log(Math.max(...marks)); // 92
console.log(Math.min(...marks)); // 78
Without the spread, Math.max(marks) would receive an array and return NaN, because Math.max expects numbers, not an array.
Example 5: a realistic React-style state update
React asks you to return new arrays and objects when state changes. Spread is the standard tool for this:
const initialState = {
items: ["pen", "book"],
user: { name: "Divya", loggedIn: false }
};
// Add an item: new array, old one untouched
const withItem = { ...initialState, items: [...initialState.items, "bag"] };
// Update one nested property: rebuild each level
const loggedIn = {
...withItem,
user: { ...withItem.user, loggedIn: true }
};
console.log(initialState.user.loggedIn); // false
console.log(loggedIn.user.loggedIn); // true
console.log(loggedIn.items); // ["pen", "book", "bag"]
Read the last example slowly: each level of the object is rebuilt with spread, and only the one property that changes is overridden. This "copy, then override" pattern is the backbone of React state updates.
Example 6: converting strings and other iterables
const letters = [..."abc"];
console.log(letters); // ["a", "b", "c"]
12. The rest parameter, and spread versus rest compared
Rest uses the same three dots as spread, but in the opposite direction. While spread expands a collection into individual pieces, rest collects individual pieces into a new array or object. The position tells you which one you are looking at.
Rest in function parameters
Placed as the last parameter, rest gathers all remaining arguments into a real array, so you can use array methods such as map, filter and reduce on it:
function total(...nums) {
return nums.reduce((sum, n) => sum + n, 0);
}
console.log(total(10, 20, 30)); // 60
console.log(total(5)); // 5
console.log(total()); // 0
Rest can follow named parameters. The named ones take their arguments first, and rest collects everything left over:
function describe(first, second, ...others) {
console.log(first, second, others);
}
describe("a", "b", "c", "d", "e");
// a b ["c", "d", "e"]
Rest in destructuring
In a destructuring pattern, rest collects the remaining elements of an array or the remaining properties of an object:
const [gold, ...restMedals] = ["gold", "silver", "bronze", "iron"];
console.log(gold); // "gold"
console.log(restMedals); // ["silver", "bronze", "iron"]
const { id, ...restUser } = { id: 1, name: "Sana", city: "Indore" };
console.log(id); // 1
console.log(restUser); // { name: "Sana", city: "Indore" }
Spread versus rest: the same dots, opposite jobs
| Question | Spread | Rest |
| Where does it appear? | On the right side of =, inside array or object literals, or in a function call | On the left side of = in a pattern, or as the last function parameter |
| What does it do? | Expands a collection into individual elements or properties | Collects individual elements or properties into one array or object |
| Example | const copy = [...arr]; | const [first, ...others] = arr; |
| Function usage | Math.max(...nums) passes array items as arguments | function f(...nums) receives arguments as an array |
| Direction | Many into one place, laid out separately | Many separate values, gathered into one |
A simple memory aid: in a function call or inside a literal, the dots spread data out; in a function definition or in a destructuring pattern, the dots rest and gather what is left.
13. A realistic example combining all three
Let us finish with one small program that uses destructuring, spread and rest together, the way they appear in real React-style code.
// A list of students and one new enrolment
const enrolled = ["Ravi", "Meera"];
const newStudent = "Asha";
// 1. Spread: build a new list without mutating the old one
const allStudents = [...enrolled, newStudent];
console.log(allStudents); // ["Ravi", "Meera", "Asha"]
// 2. Destructuring with rest: split the list
const [firstStudent, ...others] = allStudents;
console.log(firstStudent); // "Ravi"
console.log(others); // ["Meera", "Asha"]
// 3. Object destructuring with defaults and renaming in a component-style function
function StudentCard({ name, city: homeCity, course = "React JS" }) {
return name + " | " + homeCity + " | " + course;
}
console.log(StudentCard({ name: "Asha", city: "Pune" }));
// Asha | Pune | React JS
// 4. Rest parameter: a function that accepts any number of marks
function average(...marks) {
const sum = marks.reduce((total, m) => total + m, 0);
return marks.length === 0 ? 0 : sum / marks.length;
}
console.log(average(80, 90, 70)); // 80
console.log(average()); // 0
Every piece of this program is a pattern you will meet again and again in the React part of this course: building new arrays for state updates with spread, splitting data with destructuring and rest, and unpacking a props-like object with defaults in a function signature. Master these three on plain JavaScript first, and React's syntax will feel like a natural extension rather than something new to memorise.
14. Advanced and real-world usage
Once you are comfortable with the basics, destructuring, spread and rest start appearing in more sophisticated patterns. These are the ones you will meet in real projects, code reviews and React work.
Extracting methods from objects
Because destructuring works on any object, you can pull a method out of a built-in object and call it directly. This is a common idiom for console and JSON helpers:
const { log, warn, error } = console;
log("A quiet message");
warn("Something looks suspicious");
error("Something went wrong");
Building a props-like API with defaults
Libraries often accept one configuration object instead of a long list of arguments. Destructuring with defaults gives callers a friendly API where every option is optional:
function createButton({ label = "Click", size = "medium", disabled = false } = {}) {
const state = disabled ? "disabled" : size;
return "[" + label + " | " + state + "]";
}
console.log(createButton()); // [Click | medium]
console.log(createButton({ label: "Save", size: "large" })); // [Save | large]
console.log(createButton({ label: "Delete", disabled: true })); // [Delete | disabled]
Removing properties with rest
Rest destructuring is the cleanest way to strip one or more properties from an object without mutating it. The removed properties stay in the variable, the rest form a clean new object:
const user = { id: 3, name: "Farah", password: "secret123" };
const { password, safeUser } = { ...user, password: undefined };
// A simpler and more idiomatic version:
const { password: _removed, ...userWithoutPassword } = user;
console.log(userWithoutPassword);
// { id: 3, name: "Farah" }
console.log(user.password); // "secret123" (original untouched)
This "omit a key" pattern is used constantly when sending data to an API: you keep the object you have, but send a version without sensitive or irrelevant fields.
Cloning and updating in one expression
Spread and destructuring together let you copy an object, override a field and read the old value at the same time:
const cart = { items: 3, total: 450, currency: "INR" };
const { total: oldTotal } = cart;
const updatedCart = { ...cart, items: cart.items + 1, total: oldTotal + 120 };
console.log(updatedCart); // { items: 4, total: 570, currency: "INR" }
console.log(cart); // { items: 3, total: 450, currency: "INR" }
Flat function signatures with rest
Rest parameters let you design functions that feel natural to call, no matter how many values the caller has:
function joinPath(...segments) {
return segments
.filter(Boolean) // drop empty or missing parts
.join("/");
}
console.log(joinPath("home", "about")); // home/about
console.log(joinPath("https://site.com", "", "shop", "id", "9"));
// https://site.com/shop/id/9
Swapping and reordering with destructuring in loops
When you loop over an array of pairs or objects, destructuring can sit right in the loop header:
const pairs = [["a", 1], ["b", 2], ["c", 3]];
for (const [letter, number] of pairs) {
console.log(letter + " is " + number);
}
// a is 1
// b is 2
// c is 3
15. Common mistakes and the correct way
These mistakes appear in almost every beginner's first week with these features. Each one below shows the broken code first, then the fix.
Mistake 1: destructuring null or undefined
// Broken: cannot destructure null
const { name } = null; // TypeError
Correct way: guard the value with a default on the right side before destructuring:
const data = null;
const { name } = data || {};
console.log(name); // undefined (no crash)
Mistake 2: forgetting that array destructuring is positional
const person = { first: "Om", last: "Prakash" };
const [first, last] = person; // TypeError: person is not iterable
Correct way: use curly braces for objects, square brackets for arrays:
const { first, last } = person;
console.log(first, last); // Om Prakash
Mistake 3: expecting renamed variables to keep the old name
const config = { theme: "dark" };
const { theme: mode } = config;
console.log(theme); // ReferenceError: theme is not defined
Correct way: after renaming with a colon, only the new name exists:
console.log(mode); // "dark"
Mistake 4: using rest anywhere except the last position
// Broken: rest must be last
function bad(...args, last) {} // SyntaxError
Correct way: put named parameters first and rest last:
function good(last, ...args) {
console.log(last, args);
}
good("end", "a", "b"); // end ["a", "b"]
Mistake 5: thinking spread makes a deep copy
const original = { info: { city: "Delhi" } };
const copy = { ...original };
copy.info.city = "Mumbai";
console.log(original.info.city); // "Mumbai" — the inner object is shared!
Correct way: rebuild the nested level too, or use a proper deep copy when the data is deeply nested:
const safeCopy = { ...original, info: { ...original.info } };
safeCopy.info.city = "Chennai";
console.log(original.info.city); // "Mumbai" (original now safe)
Mistake 6: mutating instead of replacing with spread
const list = [1, 2, 3];
list.push(4); // mutates the original — dangerous when others hold a reference
Correct way: create a new array with spread, which is the standard React-friendly style:
const newList = [...list, 4];
console.log(list); // [1, 2, 3]
console.log(newList); // [1, 2, 3, 4]
Mistake 7: shadowing variables by destructuring with existing names
let name = "outer";
const user = { name: "inner" };
const { name } = user; // SyntaxError: name has already been declared
Correct way: rename, or reuse the existing variable with a plain assignment pattern:
let city = "outer";
const place = { city: "inner" };
({ city } = place); // parentheses needed for assignment without declaration
console.log(city); // "inner"
Mistake 8: calling a function with an array when it expects separate values
const nums = [3, 9, 1];
console.log(Math.max(nums)); // NaN
Correct way: spread the array into the call:
console.log(Math.max(...nums)); // 9
16. Best practices
Follow these habits and your code will read cleanly and behave predictably.
- Prefer
const with destructuring. Extracted values are usually not reassigned, so const communicates intent and prevents accidental overwrites.
- Destructure in the function signature. For any function that takes an options object, unpack it in the parameter list so readers see the accepted options immediately.
- Always give defaults to optional parameters. A pattern such as
{ limit = 10, page = 1 } = {} makes the function safe to call with no arguments at all.
- Use spread to replace mutation. Treat arrays and objects as unchangeable values and build new ones with spread. This habit transfers directly to React state updates.
- Rebuild nested levels when copying. Remember that spread is shallow; whenever a nested object matters, spread that level too.
- Keep rest parameters last and name them meaningfully.
...extraArgs or ...remainingItems is clearer than a bare ...args when the purpose is specific.
- Do not destructure more than you need. Pulling out ten properties when the function uses two hides the real dependencies and makes refactoring harder.
- Use renaming to avoid name clashes and improve clarity.
{ data: userData } is often better than a generic variable name in a large file.
- Use rest destructuring to omit keys safely. It avoids deleting properties from shared objects and keeps the original intact.
| Situation | Prefer | Avoid |
| Reading a few fields from an object | const { a, b } = obj; | Repeated obj.a, obj.b lookups |
| Adding an item to a list | [...list, item] | list.push(item) on shared data |
| Overriding settings | { ...defaults, ...overrides } | Manually copying property by property |
| Optional function options | function f({ size = 1 } = {}) | function f(options) with checks inside the body |
| Unknown number of arguments | function f(...items) | The old arguments object |
17. Practical project: a shopping cart mini-app
This small project uses destructuring, spread and rest together in one coherent program. You can run it in a browser console or with Node. It simulates the core logic of a shopping cart, which is exactly the kind of state manipulation React will ask of you later.
Step 1: define the initial state
const store = {
name: "Gadget Hub",
currency: "INR",
products: [
{ id: 1, title: "Mouse", price: 650 },
{ id: 2, title: "Keyboard", price: 1450 },
{ id: 3, title: "USB Cable", price: 220 }
]
};
Step 2: add a product to the cart without mutating anything
let cart = [];
function addToCart(cart, productId) {
const product = store.products.find(p => p.id === productId);
if (!product) return cart;
return [...cart, product]; // new array, original untouched
}
cart = addToCart(cart, 1);
cart = addToCart(cart, 3);
console.log(cart.length); // 2
Step 3: remove a product using rest destructuring
function removeFromCart(cart, productId) {
return cart.filter(item => item.id !== productId);
}
cart = removeFromCart(cart, 1);
console.log(cart.map(item => item.title)); // ["USB Cable"]
Step 4: summarise the cart with destructuring and rest
function cartSummary({ name: storeName, currency }, ...items) {
const total = items.reduce((sum, { price }) => sum + price, 0);
const titles = items.map(({ title }) => title);
return storeName + ": " + titles.join(", ") + " = " + currency + " " + total;
}
console.log(cartSummary(store, ...cart));
// Gadget Hub: USB Cable = INR 220
Notice how much work is done in the signature: the store object is destructured with renaming, the items arrive through a rest parameter, and each item is destructured inside reduce and map to read only price and title.
Step 5: apply a coupon by copying and overriding
function applyDiscount(summary, percent) {
return { ...summary, total: Math.round(summary.total * (1 - percent / 100)) };
}
const summary = { items: cart.length, total: 220 };
const discounted = applyDiscount(summary, 10);
console.log(discounted); // { items: 1, total: 198 }
console.log(summary); // { items: 1, total: 220 } (original safe)
Step 6: destructure the final result for display
const { items, total } = discounted;
console.log("You bought " + items + " item(s) for Rs. " + total);
// You bought 1 item(s) for Rs. 198
What this project teaches
- Building new arrays with spread instead of pushing into shared ones.
- Using rest parameters to accept a flexible list of items.
- Destructuring objects inside
map, filter and reduce callbacks.
- Renaming properties in a signature to avoid clumsy names.
- Copying and overriding objects to represent state changes.
18. Practice Exercises
- Given
const nums = [10, 20, 30, 40, 50];, destructure it in one line so that a is 10, b is 20, and rest is [30, 40, 50].
- Given
const book = { title: "JS Basics", author: { first: "Leela", last: "Nair" }, pages: 210 };, extract title, first and pages in a single nested destructuring statement.
- Write a function
greet({ name = "Guest", time = "morning" } = {}) that returns "Good morning, Guest!" when called with no arguments, and works correctly for any provided values.
- Merge
const a = { x: 1, y: 2 }; and const b = { y: 9, z: 3 }; into one object where y is 9, without changing a or b.
- Write
function biggest(...nums) that returns the largest number passed, and returns undefined gracefully when called with none.
- Swap the values of
let p = "first" and let q = "second" in a single line using destructuring.
- Given
const user = { id: 5, name: "Ravi", email: "[email protected]" };, produce a new object containing everything except email, using rest destructuring.
- Convert the string
"react" into the array ["r", "e", "a", "c", "t"] using spread, then join it back into a string with dashes between letters.
- Given an array of student objects, use destructuring inside
map to return an array of strings in the form "Name: 82" from name and marks properties.
- Write
function describePoint([x, y] = [0, 0]) that accepts an array of two numbers and returns "Point at x, y", working when called with no argument.
19. Interview Questions and Answers
What is destructuring and why is it useful?
Destructuring is a syntax feature that unpacks values from arrays or properties from objects into separate variables using a pattern on the left side of an assignment. It is useful because it removes repetitive one-line-per-value extraction, makes function signatures self-documenting, and lets you work directly with the pieces of data you need.
What is the difference between the spread operator and rest parameters?
They use the same three-dot syntax but work in opposite directions. Spread expands an existing array or object into individual elements or properties, and appears on the right side of assignments, inside literals, or in function calls. Rest collects multiple individual values into one array or object, and appears as the last function parameter or at the end of a destructuring pattern.
How do you provide default values in destructuring?
Write = followed by the fallback inside the pattern. For arrays: const [a = 5] = [];. For objects: const { role = "student" } = user;. The default is applied only when the extracted value is undefined. For function parameters, also add = {} after the whole pattern so the function survives being called with no argument.
How do you rename a variable while destructuring an object?
Use a colon: const { price_inr: price } = product; stores the price_inr property in a variable called price. After renaming, only the new name exists. You can combine renaming with a default: const { region: country = "India" } = config;.
Is spread a deep copy or a shallow copy?
Spread performs a shallow copy. The new array or object is independent at the top level, but any nested arrays or objects are still shared references with the original. Changing a nested value through the copy changes the original too. For deeply nested data you must rebuild each nested level with additional spreads or use a deep copy approach.
Why does React code rely so heavily on the spread operator?
React expects state updates to produce new arrays and objects rather than mutate existing ones, because change detection compares references. Spread is the standard way to build a new array with an item added or removed, or a new object with one property overridden, while leaving the previous state untouched.
What is the rest property in object destructuring used for?
It gathers the remaining properties of an object into a new object. Its most common practical use is removing one or more keys without mutating the original, for example const { password, ...safeUser } = user;, which produces a copy of the user without the password field.
Why is the rest parameter better than the older arguments object?
The rest parameter is a real array, so array methods such as map, filter and reduce work on it directly. The old arguments object is array-like but not an array, requires conversion, cannot be used with arrow functions in the same way, and does not combine with named parameters as cleanly.
What happens if you destructure more positions than an array has elements?
The extra variables receive undefined. If a default value is written for those positions, the default is used instead. No error is thrown, which is why defaults are recommended whenever the data length is uncertain.
Can you destructure inside a loop?
Yes. In a for...of loop you can place the destructuring pattern directly in the header, for example for (const [key, value] of entries) or for (const { name, marks } of students). Each iteration unpacks the current element before the loop body runs.
How do you safely destructure a value that might be null or undefined?
Give the right-hand side a fallback before destructuring, such as const { name } = maybeUser || {};, or provide a default object in a parameter pattern with = {}. Destructuring null or undefined directly throws a TypeError, so the fallback prevents the crash.
How would you merge two objects where the second overrides the first?
Spread both into a new object literal with the overriding object last: const merged = { ...defaults, ...overrides };. Because later properties overwrite earlier ones with the same key, the second object's values win, and both originals remain unchanged.
20. Quick Revision Checklist
- I can explain destructuring in one sentence: unpacking array values or object properties into variables with a pattern.
- I know array destructuring matches by position and object destructuring matches by property name.
- I can skip positions with empty commas and swap two variables in one line.
- I can rename with a colon, set defaults with an equals sign, and reach into nested objects and arrays.
- I destructure options objects in function signatures and add
= {} for safety.
- I know spread appears on the right (expand) and rest appears on the left or last in parameters (collect).
- I use
[...list, item] and { ...obj, key: newValue } instead of mutating shared data.
- I know spread is a shallow copy and rebuild nested levels when needed.
- I can omit a key with
const { key, ...rest } = obj;.
- I can pass an array as separate arguments with
fn(...arr) and accept any number of arguments with function fn(...args).
21. Official Documentation and Further Reading
These resources from the course reading list expand on the ideas covered here and show how destructuring, spread and rest are used in real React work:
Conclusion
Destructuring, spread and rest are three sides of the same idea: treating arrays and objects as flexible collections you can unpack, expand and regather with almost no ceremony. Destructuring pulls exactly the values you need into clearly named variables, spread builds new arrays and objects from old ones without mutation, and rest gathers whatever is left over into a tidy collection. Together they replace pages of repetitive, error-prone code with short, readable expressions.
These are not exotic features reserved for experts; they are the everyday grammar of modern JavaScript. Every React component you write will destructure its props, every state update will use spread to create new data, and every flexible utility function you build will use rest to accept its arguments. Practise the patterns on this page until they feel automatic, because in the React module that follows, they will appear so often that you will stop noticing them as separate features and simply read them as part of the language.
Learn more in the React JS Training course, or register for a course demo.