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.name does not affect the original.
  • Nested objects and arrays are references to the same memory, so changing copy.address.city also changes original.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};
6
7const copy = { ...original };
8
9copy.name = "Grace"; // top-level primitive: independent
10copy.address.city = "Paris"; // nested object: shared!
11copy.tags.push("editor"); // nested array: shared!
12
13console.log(original.name); // Ada
14console.log(original.address.city); // Paris
15console.log(original.tags); // ["admin", "editor"]
16console.log(copy.address === original.address); // true
17
18// Correct immutable update: copy each level you change
19const updated = { ...original, address: { ...original.address, city: "Rome" } };
20console.log(original.address.city, updated.address.city); // Paris Rome
21
22// Arrays behave the same way
23const matrix = [[1, 2], [3, 4]];
24const rows = [...matrix];
25rows[0].push(99);
26console.log(matrix[0]); // [1, 2, 99] - inner arrays are shared
27
28// Spread loses the prototype
29class 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.

Open in study app