Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 6.3 — Destructuring and Spread with Objects
JavaScript · Example 4 of 4 ES2018+

Spread is shallow

Changing copy.name didn't touch the original, but both objects hold the same members array. Topic 6.5 shows how to copy nested data too.

Destructuring pulls properties out of an object into variables in one line, with renaming, defaults and a rest object for whatever is left; spread ... copies one object's properties into a new one, which is how you merge objects.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Given const movie = { title: "Lagaan", year: 2001, rating: null }, destructure title into name, year, and rating with a default of "not rated". Log all three and explain the rating.

02

Write withoutKeys(obj) that returns a copy of obj without createdAt and updatedAt, leaving the original unchanged.

03

Write updateEmail(user, email) that returns a new user with the new email, without changing user. Prove it by logging both.

Explain it without notes

01

Explain object destructuring with renaming and defaults, and when a default is used.

02

What's the difference between object rest and object spread?

03

Why is { ...obj } called a shallow copy, and what bug does that cause?

04

How does spread differ from Object.assign?

Spread is shallow ES2018+

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Team A [ 'Asha', 'Ravi', 'Meera' ]
Team B [ 'Asha', 'Ravi', 'Meera' ]
true