JavaScriptEasy
What is a shallow copy?
A shallow copy creates a new top-level object or array, but nested objects inside it are still shared by reference with the original.
Ways to make one
- Arrays:
[...arr],arr.slice(),Array.from(arr),arr.concat(). - Objects:
{ ...obj },Object.assign({}, obj).
What is copied and what is shared
- Primitive values at the top level are copied, so changing
copy.namedoes not affect the original. - Nested objects and arrays are references to the same memory, so changing
copy.address.cityalso changesoriginal.address.city.
When a shallow copy is enough
- The data is flat (only primitives).
- You only change top-level fields.
- You are doing immutable updates and will also copy each nested level you change (
{ ...state, user: { ...state.user, name } }). This is exactly how React and Redux updates work and is efficient because unchanged branches are shared.
What spread does not copy
- The prototype (the copy is a plain object, so class methods are lost).
- Non-enumerable properties and getters as getters (they are evaluated into plain values).
- Symbols are copied by spread and
Object.assign.
When you need more
Use a deep copy (structuredClone) when you plan to mutate nested data freely and need the original to stay untouched.
Code example
js
1const original = {2 name: "Ada",3 tags: ["admin"],4 address: { city: "London" },5};67const copy = { ...original };89copy.name = "Grace"; // top-level primitive: independent10copy.address.city = "Paris"; // nested object: shared!11copy.tags.push("editor"); // nested array: shared!1213console.log(original.name); // Ada14console.log(original.address.city); // Paris15console.log(original.tags); // ["admin", "editor"]16console.log(copy.address === original.address); // true1718// Correct immutable update: copy each level you change19const updated = { ...original, address: { ...original.address, city: "Rome" } };20console.log(original.address.city, updated.address.city); // Paris Rome2122// Arrays behave the same way23const matrix = [[1, 2], [3, 4]];24const rows = [...matrix];25rows[0].push(99);26console.log(matrix[0]); // [1, 2, 99] - inner arrays are shared2728// Spread loses the prototype29class Point {30 constructor(x) { this.x = x; }31 move() { return this.x + 1; }32}33const p = { ...new Point(1) };34console.log(p.x, typeof p.move); // 1 "undefined"
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.