Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 5.10 — Copying: Shallow vs Deep
JavaScript · Example 2 of 3 ES2018+

The shallow copy trap, and two fixes

The shallow copy shared Asha's object, so her score changed in team too (the page shows 99). structuredClone shares nothing. The map + object spread (ES2018) update copies only Ravi's object and reuses Asha's.

Assigning an array to another variable copies only the reference, so both names point at the same array; spread, slice and Array.from make a shallow copy (a new outer array sharing the same inner objects), and structuredClone makes a deep copy where nothing is shared.

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 6 hands-on exercises with automatic checks.

Practice questions

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

01

Make a copy of const prices = [10, 20, 30]; that you can sort descending without changing prices, in two different ways.

02

Given const users = [{ id: 1, active: false }, { id: 2, active: false }];, return a new array where user 2 is active, without changing users, and prove it.

Explain it without notes

01

What is the difference between a shallow copy and a deep copy of an array?

02

Why does [1, 2] === [1, 2] return false?

03

What can structuredClone copy that JSON.parse(JSON.stringify()) can't, and what can't it copy?

04

How do you update one object inside an array without mutating the original array?

The shallow copy trap, and two fixes ES2018+

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

99
false true
7 0 false
7 8 true