🟨 JavaScript tutorial for beginners · Class 9 · Lesson 7 of 18 · Free
Destructuring & Spread – Unpack and Copy Data in JavaScript
⏱ About 35 minutes · ▶ run real JavaScript here — nothing to install · no sign-in
In this lesson you will
- Unpack values from arrays and objects into variables with destructuring
- Copy and merge arrays and objects with the spread operator (...)
- Collect "the rest" of the values with the rest operator in arrays and functions
Your teacher sends the marks as one array: [92, 78, 85]. Writing marks[0], marks[1], marks[2] again and again is slow and easy to mix up. Destructuring lets you unpack them into maths, science and english in one line, and spread lets you copy or join data without breaking the original.
How do I unpack an array into variables in JavaScript?
Array destructuring puts square brackets on the LEFT side of =. Each name takes the value at the same position.
The first name gets item 0, the second gets item 1, and so on. The array itself does not change.
Leave a gap with an extra comma to skip a value. Give a default with = in case the value is missing.
▶const marks = [92, 78, 85];2const [maths, science, english] = marks;3console.log("Maths:", maths);4console.log("English:", english);56const [first, , third] = ["Rohit", "Virat", "Shubman"];7console.log(first, third);89const [runs, balls = 6] = [24];10console.log(runs, balls);
No variables yet.
▌✏️ Change this code and run it yourself
Maths: 92English: 85Rohit Shubman24 6
💡 Try it: add a fourth subject to marks and a fourth name on the left, then run again.
How does object destructuring work in JavaScript?
Object destructuring uses curly braces { } on the left. Here the NAME matters, not the position.
{ name, city } looks for keys called name and city inside the object. A key that is not there gives undefined, unless you give a default.
Want a different variable name? Write key: newName. So { name: studentName } reads the key name into a variable called studentName.
▶const student = { name: "Asha", cls: 9, city: "Pune" };2const { name, city } = student;3console.log(name, "lives in", city);45const { cls: grade, house = "Green" } = student;6console.log("Class", grade, "House", house);78const ticket = { train: "Deccan Queen", seat: { coach: "C2", no: 41 } };9const { seat: { coach, no } } = ticket;10console.log(`Coach ${coach}, seat ${no}`);
No variables yet.
▌✏️ Change this code and run it yourself
Asha lives in PuneClass 9 House GreenCoach C2, seat 41
💡 Try it: change house = "Green" to a real key like city = "Delhi". Which value wins?
How do I use destructuring in function parameters and loops?
You can destructure right inside the brackets of a function. The function then picks only the keys it needs.
This is very common in real projects. The caller passes one object, and the order of keys does not matter.
for…of loops can destructure each item too. Object.entries() gives [key, value] pairs, which you unpack with [ ].
Smriti: 45 off 30 (SR 150.0)Mon: ₹20Tue: ₹0Wed: ₹35coffee tea
💡 The last three lines swap two variables in one step, with no extra temp variable.
What does the spread operator (...) do with arrays in JavaScript?
Three dots before an array spread it out into separate values. [...marks] means "all the items of marks, one by one".
Use it to copy an array, to join arrays, or to pass the items to a function like Math.max().
Why copy? In Class 8 you saw that const b = a does NOT copy an array. Both names point to the SAME array. A spread copy is a new array, so changing it leaves the original safe.
▶const termOne = [72, 85];2const termTwo = [90, 64];3const allTests = [...termOne, ...termTwo, 99];4console.log(allTests);5console.log("Best:", Math.max(...allTests));67const sameList = termOne;8const copy = [...termOne];9copy.push(100);10sameList.push(50);11console.log("termOne:", termOne);12console.log("copy:", copy);
No variables yet.
▌✏️ Change this code and run it yourself
[72, 85, 90, 64, 99]Best: 99termOne: [72, 85, 50]copy: [72, 85, 100]
💡 Try it: remove the dots in Math.max(allTests) and run. You get NaN, because max gets one array, not numbers.
How do I copy and update an object with spread?
Spread works inside { } too. { ...student } makes a new object with the same keys and values.
Put new keys after the spread to change or add them. When a key appears twice, the LAST one wins.
This is how apps update data safely: make a new copy with the change, instead of changing the old object.
{ roti: 2, sabzi: "aloo", sweet: false }{ roti: 2, sabzi: "paneer", sweet: true }{ theme: "dark", sound: true }
💡 Spread copies only one level deep. An object inside an object is still shared (see Common mistakes).
What is the rest operator in JavaScript and how is it different from spread?
The same three dots do the opposite job on the LEFT side of = or in function parameters. There they COLLECT values into an array or object. This is called rest.
Easy rule: ... in a value spreads out; ... in a name gathers up. Rest must always be the last name.
A function with ...numbers can take any number of arguments. Inside, numbers is a normal array.
Captain: HarmanpreetOthers: ["Smriti", "Jemimah", "Deepti"]Kabir { maths: 88, hindi: 79 }Canteen bill: ₹65
💡 Try it: call total() with five prices, or with none. What does it return for none?
🤔 Predict the output
Think like JavaScript: read the code and choose what it prints. You get the reason straight away.
Question 1. What does this print?
const [a, , b] = [10, 20, 30]; console.log(a, b);
Question 2. What does this print?
const { name, city = "Pune" } = { name: "Ravi", city: "Delhi" };
console.log(city);Question 3. What does this print?
const a = [1, 2]; const b = a; const c = [...a]; b.push(3); console.log(a.length, c.length);
🧩 Your challenge
Build a cricket scorecard. Each player is an object { name, scores }. For each player, use destructuring to get name and scores, use spread to add the new match score WITHOUT changing the old array, and find the best score with Math.max(...). Print lines like: Rohit: [45, 12, 87, 60] best 87 Then print the original players[0].scores to prove it did not change.
Rohit: [45, 12, 87, 60] best 87 Smriti: [33, 91, 8, 54] best 91 Old Rohit scores: [45, 12, 87]
⚠️ Common mistakes (and how to fix them)
❌ Wrong
function greet({ name }) {
console.log("Hi " + name);
}
greet();TypeError: Cannot destructure property 'name' of 'undefined' as it is undefined.
✅ Right
function greet({ name = "friend" } = {}) {
console.log("Hi " + name);
}
greet();You cannot destructure undefined. If the object may be missing, give the whole parameter a default = {}.
❌ Wrong
const marks = { maths: 90, science: 85 };
const copy = [...marks];
console.log(copy);TypeError: marks is not iterable
✅ Right
const marks = { maths: 90, science: 85 };
const copy = { ...marks };
console.log(copy);[...x] only works on things you can loop over, like arrays and strings. To copy an object, spread it inside { }.
❌ Wrong
const asha = { name: "Asha", marks: { maths: 80 } };
const copy = { ...asha };
copy.marks.maths = 100;
console.log(asha.marks.maths);No error, but it prints 100: changing the copy also changed Asha's real marks, because both share the same inner object.
✅ Right
const asha = { name: "Asha", marks: { maths: 80 } };
const copy = { ...asha, marks: { ...asha.marks } };
copy.marks.maths = 100;
console.log(asha.marks.maths);Spread is a shallow copy: the inner marks object is still shared. Spread the inner object too (or use structuredClone(asha)).
📌 Remember
- const [a, b] = array unpacks by position; const { a, b } = object unpacks by key name.
- Use key: newName to rename and = value to give a default for a missing value.
- ... on the right side (spread) expands an array or object: copy, merge, or pass to Math.max(...).
- When two objects are spread together, the last value for a key wins.
- ... on the left side or in parameters (rest) collects the leftover values; it must come last.
- Spread copies only one level deep — inner arrays and objects are still shared.
Finished the quiz and the challenge?
Questions students ask
What is destructuring in JavaScript in simple words?
Destructuring is a short way to take values out of an array or object and store them in variables. Instead of writing marks[0] and marks[1], you write const [maths, science] = marks. It does not change the array or object.
What is the difference between spread and rest in JavaScript?
Both use three dots. Spread is used where a value goes and expands an array or object into pieces. Rest is used where a name goes (left of = or in parameters) and collects pieces into one array or object.
Does the spread operator make a deep copy?
No. Spread makes a shallow copy: the top level is new, but objects or arrays inside are shared. For a full deep copy of plain data, use structuredClone(value).
Can I use destructuring with function return values?
Yes. A function can return an array or an object, and you unpack it straight away, like const [min, max] = getRange(marks). This is a neat way to return more than one value.