Skip to the content

Copies and references

JavaScript · Unit 15: Immutability

You already know = doesn't copy an object: it gives it a second name. And that { ...obj } does build a new one, but only the first level.

That's called a shallow copy: if there's another object inside, the copy and the original share that inner object.

const a = { n: 1, sub: { m: 2 } };
const b = { ...a };
b.n = 9;
b.sub.m = 9;
console.log(a.n, a.sub.m);

Prints

1 9

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    The order gets copied and two things change. What does it print?

  2. 2. Multiple choice

    user holds name and addr, and addr is another object. What does { ...user } create?

  3. 3. Complete the code

    Fill in the blank so bumping the copy's points doesn't bump Leo's.

  4. 4. Complete the code

    Fill in the blank so the copy carries new objects, not the same ones.

  5. 5. Predict the output

    Two copies of the same list, made in different ways. What does it print?

  6. 6. Find the bug

    r should be a copy of b that stands on its own: signing Leo up in r should leave b's crew with Ana alone. Which line has the error?

  7. 7. Predict the output

    The record is copied with the JSON round trip. What does it print?

  8. 8. Multiple choice

    When does copying with JSON.parse(JSON.stringify(x)) not work?

  9. 9. Put the lines in order

    Put the program in order: it copies the recipe deeply and adds garlic to the copy only.

  10. 10. Predict the output

    The function hands out a bonus. What does it print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →