Skip to the content

Copying and spreading

JavaScript · Unit 8: More on arrays

Remember birthday(p), which added 1 to p.age? What you didn't see is that the person you passed in also got a year older outside the function.

That's because a variable doesn't hold a copy of an array or object: it points to it. If two names point to the same data, a change shows through both.

const a = ["bread"];
const b = a;
b.push("salt");
console.log(a);

Prints

[ 'bread', 'salt' ]

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

    What does this code print?

  2. 2. Predict the output

    What does this code print?

  3. 3. Predict the output

    What does this code print?

  4. 4. Multiple choice

    If a is an array, what does const b = a; do?

  5. 5. Complete the code

    Complete it to sort a copy and leave nums as it was.

  6. 6. Find the bug

    The function should return the prices sorted without touching the array it gets. Here it should print 60 12. Which line has the error?

  7. 7. Predict the output

    What does this code print?

  8. 8. Predict the output

    What does this code print?

  9. 9. Predict the output

    Look at where the three dots go. What does it print?

  10. 10. Put the lines in order

    Order the lines to give Liam a copy of your list, have him add grapes, and keep yours the same.

  11. 11. Predict the output

    What does this code 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 →