Copying and spreading
JavaScript · Unit 8: More on arrays
- Full plan
- JavaScript
- 11 exercises
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. Predict the output
What does this code print?
2. Predict the output
What does this code print?
3. Predict the output
What does this code print?
4. Multiple choice
If
ais an array, what doesconst b = a;do?5. Complete the code
Complete it to sort a copy and leave
numsas it was.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. Predict the output
What does this code print?
8. Predict the output
What does this code print?
9. Predict the output
Look at where the three dots go. What does it print?
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. Predict the output
What does this code print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.