Command Palette

Search for a command to run...

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

Rename and defaults

age was missing, so its default was used. role was null, which is not undefined, so the default "guest" was not used. Defaults ignore 0 and "" 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?

Rename and defaults ES2015+

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Meera Delhi 18 null
0 ""