Beginner · 9 min
Spread and rest
Copy a collection and collect an unknown number of arguments.
Copy and extend
Spread syntax expands an array into another array. For objects, it copies own enumerable properties. These copies are shallow: nested objects remain shared.
const original = ["Read", "Practice"];
const updated = [...original, "Review"];
console.log(original.length);
console.log(updated.join(", "));Output
2 Read, Practice, Review
Collect arguments
A rest parameter gathers remaining arguments into an array. It must be the last parameter.
function total(...values) {
return values.reduce((sum, value) => sum + value, 0);
}
console.log(total(2, 3, 4));Output
9
Put it into practice
- Predict each result before running the example.
- Complete the coding task, then explain why your solution works.
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Extend without mutation
Create updated by copying tasks and adding "Review". Keep tasks unchanged and display both lengths.
Use [...tasks, "Review"] to create a new array.