Copying values: spread and Object.assign

A copy is what a program wants when two parts must not see the changes of the other. Primitives already behave that way, and the previous lesson showed that objects do not: a second binding is a second name for one object. To get a real copy you create a new object and fill it with the entries of the old one, and JavaScript has two short ways to do that, the spread syntax and Object.assign.

Both make a shallow copy. The new object is a new object, its own properties are new bindings, and every object stored inside it is still shared with the original. That is enough for a settings object of strings and numbers and not enough for a tree, which the next lesson clones in full.

What copies and what shares

The program below puts the two behaviours next to each other. shared is a second name for the settings object, so the write through it is visible through settings. copied is a new object, so the write through it stays in the copy, and the original keeps the value it had.

const settings = { theme: 'dark', fontSize: 14 }; const shared = settings; shared.fontSize = 20; console.log('through the alias:', settings.fontSize); const copied = { ...settings }; copied.fontSize = 12; console.log('through the copy:', settings.fontSize); console.log('a new object:', copied !== settings);

node shared.mjs

through the alias: 20
through the copy: 20
a new object: true

The second line prints 20 as well, and that is the point of the order: the alias had already changed the original before the copy was made, so the copy started from 20. The last line is the proof that copied is a different value, which the previous lesson showed is what !== reports for objects.

The spread copy

Three dots in front of an array or an object spread its elements or entries into a new literal. [...source] builds a new array with the same elements, and { ...draft } builds a new object with the same properties. Adding a property after the spread overrides the one that was copied, which is how a draft becomes a published record without a second statement.

const source = [1, 2, 3]; const copy = [...source]; copy.push(4); console.log('source:', source.join(', ')); console.log('copy:', copy.join(', ')); console.log('a new array:', copy !== source); const draft = { title: 'Notes', done: false }; const published = { ...draft, done: true }; console.log('draft:', JSON.stringify(draft)); console.log('published:', JSON.stringify(published));

node spread.mjs

source: 1, 2, 3
copy: 1, 2, 3, 4
a new array: true
draft: {"title":"Notes","done":false}
published: {"title":"Notes","done":true}

The push reached the copy only, and the draft kept done: false because the spread built a new object and the done: true after it wrote into that new object. The order of the entries in an object literal decides the winner, which the lesson on spread and rest takes further.

Object.assign

Object.assign(target, ...sources) writes every property of every source into the target, from left to right, and returns the target. Called with an empty object as the target it builds a copy; called with an existing object it changes that object and hands it back, which is a different thing with a different name.

const defaults = { theme: 'light', fontSize: 14 }; const user = { fontSize: 18 }; const merged = Object.assign({}, defaults, user); console.log('merged:', JSON.stringify(merged)); const target = { a: 1 }; const same = Object.assign(target, { b: 2 }); console.log('target:', JSON.stringify(target)); console.log('same object:', same === target);

node assign.mjs

merged: {"theme":"light","fontSize":18}
target: {"a":1,"b":2}
same object: true

The first call left defaults and user untouched, because the empty literal was the target. The second call wrote b into target and returned that same object, which the last line proves. A function that is given an object to fill should say so in its name, the way Object.assign does by returning its first argument.

A shallow copy shares the inside

A spread or an Object.assign copies one level. The new object has its own property slots, and a property whose value is an object holds a copy of the reference to that inner object. Change the inner object through the copy and the original sees it, because there is still one inner object.

const original = { name: 'Ada', address: { city: 'London' } }; const copy = { ...original }; copy.name = 'Grace'; copy.address.city = 'Paris'; console.log('name:', original.name); console.log('city:', original.address.city); console.log('nested object shared:', original.address === copy.address);

node shallow.mjs

name: Ada
city: Paris
nested object shared: true

The outer property changed in the copy only, and the inner one changed everywhere. The last line names the cause, and the next lesson replaces the shallow copy with structuredClone, which walks the whole tree.

Exercises

  1. Move the const copied = { ...settings }; line above the alias write in shared.mjs. What does the second line of the output become, and why?
  2. Add [0, ...source] to spread.mjs as a new binding and print it. How many elements does the new array have?
  3. Call Object.assign(defaults, user) in assign.mjs instead of the empty target. What does defaults print, and what does that say about the first argument?
  4. Make the shallow copy in shallow.mjs deep for this one field with { ...original, address: { ...original.address } }. Which line of the output changes?
  5. Copy an array that holds an object, change the object through the copy, and print the original. Explain the result with the word reference.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does const copy = { ...original }; create?

    Answer

    A new object with the same own properties

    The spread copies the own properties into a new object, one level deep.

  2. What does this program print? const a = { n: 1 }; const b = { ...a }; b.n = 2; console.log(a.n);

    Answer

    1

    The copy has its own n property, so the write through b never reaches a.

  3. What does this program print? const list = [1, 2]; const copy = [...list]; copy.push(3); console.log(list.length);

    Answer

    2

    The spread built a new array, so the push changed the copy and the original kept two elements.

  4. What does this program print? const defaults = { theme: "light" }; const user = { theme: "dark" }; const result = Object.assign({}, defaults, user); console.log(result.theme);

    Answer

    dark

    The sources are written into the target from left to right, so the later user object wins.

  5. What does this program print? const a = { inner: { n: 1 } }; const b = { ...a }; b.inner.n = 2; console.log(a.inner.n);

    Answer

    2

    The spread is shallow, so both objects hold the same inner object and the write is seen through a.

  6. What does Object.assign(target, source) return?

    Answer

    The target object, after the copy

    The function writes into the first argument and returns it, which is why an empty literal is the usual target for a copy.

  7. Why is a shallow copy not enough for a tree of objects?

    Answer

    Because the nested objects are still shared with the original

    One level is copied, and every object inside keeps its reference, so a change in a nested object is seen by both sides.

  8. Which line makes a new array with the elements of source?

    Answer

    const copy = [...source];

    The square brackets make an array literal and the three dots spread the elements into it.

  9. What does this program print? const draft = { title: "Notes", done: false }; const published = { ...draft, done: true }; console.log(draft.done);

    Answer

    false

    The later property went into the new object, so the draft still holds its own done value.

  10. What happens to the first argument of Object.assign({}, defaults)?

    Answer

    The empty object receives the properties and is returned

    The empty literal is the target, so it gains the defaults and comes back as the result of the call.

The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image