Rest Parameters

The full text of this chapter, to read or revisit. To practise, do the exercises.

▶ Do the exercises

Exercise 1 — Gathering Arguments Into an Array

Imagine you want to write a function that heals your Codémon after a battle — sometimes 2 Codémon, sometimes 3, sometimes 6. Defining a fixed list of parameters quickly breaks down when you pass fewer arguments than expected:

function healTeam(cdm1, cdm2, cdm3) { console.log("Healing: " + cdm1 + ", " + cdm2 + ", " + cdm3); } healTeam("Aquachu", "Zap", "Pyrochu"); healTeam("Aquachu", "Zap"); // Healing: Aquachu, Zap, undefined

To let a function accept any number of arguments, write three dots (`...`) before the parameter name. This is called a rest parameter: it gathers all passed arguments into a single array:

function healTeam(...team) { console.log(team); } healTeam("Aquachu", "Zap", "Pyrochu"); healTeam("Aquachu", "Zap");

Exercise 2 — It's a Real Array

Inside the function, a rest parameter is a genuine JavaScript array. That means you can use `.length`, loops, or any array method like `forEach` on it:

function announce(...names) { console.log("Fighters: " + names.length); names.forEach((name) => console.log("- " + name)); } announce("Aquachu", "Zap", "Pyrochu");

Even if you call the function with no arguments at all, the rest parameter is never `undefined` — it is simply an empty array `[]`, so `.length` and loops work without crashing:

function announce(...names) { console.log("Fighters: " + names.length); console.log(names); } announce();

Exercise 3 — Quiz: How Many Gathered?

What does this code print?

function count(...items) { return items.length; } console.log(count("a", "b", "c", "d"));
Options
• 4
• 1
• 0
• undefined

Hint : Every argument ends up in the same array.

Exercise 4 — Gather Them All

Make the function accept any number of moves and print how many there are.

Hint : One symbol gathers the arguments, and the result is counted like any array.

Exercise 5 — It Must Come Last

A rest parameter can follow normal parameters: those are filled first, and everything left over is gathered:

function battle(champion, ...challengers) { console.log("Champion: " + champion); console.log("Challengers: " + challengers.length); } battle("Metachu", "Aquachu", "Zap", "Pyrochu");

Always last

There can be only one rest parameter, and it must be the last one. `function f(...a, b)` is a syntax error: nothing could ever reach `b`.

Exercise 6 — Quiz: What's Left Over

What does this code print?

function f(first, ...others) { return others.length; } console.log(f("a", "b", "c"));
Options
• 2
• 3
• 1
• 0

Hint : The named parameter takes its share before the gathering starts.

Exercise 7 — Rest vs Spread

Same three dots, opposite jobs. What tells them apart is where you write them:

function total(...numbers) { let sum = 0; for (let n of numbers) { sum += n; } return sum; } const levels = [10, 20, 30]; console.log(total(10, 20, 30)); console.log(total(...levels));

Exercise 8 — Three Dots, Two Jobs

Match each use of `...` with its role.

Items to match
• function f(...args)
• f(...array)
• [...array, 3]
• { ...object }
Definitions
• Rest: gathers into an array
• Spread: pours out as arguments
• Spread: builds a new array
• Spread: copies the properties

Exercise 9 — Damage Log

Write a logger that accepts any number of hits in a single call.

Step 1: `logHits(name, ...hits)` receives a Codémon name, then any number of damage numbers. Step 2: it prints one line per hit, in the format `"name takes X"`. Step 3: it returns the total damage. If no hit is passed, it returns 0. Step 4: call it with three hits and print the returned total, then call it with no hit at all and print that total too.

Expected output:

Zap takes 10 Zap takes 25 Zap takes 5 Total: 40 Total: 0
Starter code
// Write your function here // Use it here
Back to the course