Destructuring and spread
You'll learn to pull values out of objects and arrays with destructuring, and to copy them with spread (...).
const { name } = props, const [count, setCount] = useState(0), and { ...user, name } to update state.Watch & read
Start with the required ones. The others are there when you need them.
Explanation
You have an object, like a student's result, and you need three of its values. Writing
result.name, result.marks and result.grade again and again is long. You can unpack them in one line.
This is called destructuring.
Think of opening a parcel and placing each item on the table with its own label.
const result = { name: "Nusrat", marks: 82, grade: "A" };const { name, marks } = result;console.log(name, marks); // Nusrat 82
With { } on the left, JavaScript looks for keys with the same names and makes a variable for each.
For arrays you use [ ], and the values are taken by position, not by name:
const [first, second] = ["Tamim", "Liton"];// first is "Tamim", second is "Liton"
The three dots ... are called spread. They spread out every item of an array, or every key of an
object, into a new one. That is how you make a copy with one thing changed:
const player = { name: "Shakib", runs: 45 };const updated = { ...player, runs: 50 };// player.runs is still 45, updated.runs is 50
Read { ...player, runs: 50 } as: copy everything from player, then set runs to 50. Order matters:
a key written after the spread wins. For arrays, [...marks, 90] is a new array with 90 added at the end.
People often spell a key differently when destructuring: const { nam } = result gives undefined,
with no error. The name on the left must match the key exactly. Another common mistake is changing the
original (player.runs = 50) when the code needed a copy. In React, that bug makes the screen not update.
When you read code, look at the left side of =. { } or [ ] there means destructuring. ... on
the right side, inside { } or [ ], means a new copy is being made.
Code tour
Click a line number with a ring to read the note for that line.
Practice
Short drills. Take your time and read the code before you answer.
1const player = { name: "Shakib", runs: 45 };2const updated = { ...player, runs: 50 };3console.log(player.runs, updated.runs);
addRuns should return a new player with more runs, and leave the original player unchanged. Right now it changes the original. Fix it so all checks pass.Quick check
3 questions. Each one explains itself after you answer.
- 1 / 3After
const { city } = { name: "Rafi", city: "Sylhet" };, what iscity? - 2 / 3After
const [a, b] = [10, 20, 30];, what isb? - 3 / 3
const bigger = [...marks, 90];What happens tomarks?
Explain it back
How confident are you with Destructuring and spread?
Done
{ ...obj, key: value } as a changed copy.