×

typescript · level 3 · unit 1 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Take any number of arguments with a .

Some functions should accept as many arguments as you like: total(2, 5) or total(2, 5, 9, 1). Put three dots before the last parameter, ...prices: number[], and it becomes a rest parameter: an array holding every leftover argument.

Three dots also work the other way. In a call, total(...basket) is a : it unpacks an array into separate arguments. If a function wants exactly two arguments, the checker needs a tuple, like [number, number], to know the count fits.

function total(...prices: number[]): number {
  let sum = 0;
  for (const price of prices) {
    sum = sum + price;
  }
  return sum;
}
console.log(total(2, 5));
console.log(total(2, 5, 9, 1));
const basket: number[] = [3, 4, 3];
console.log(total(...basket));

A rest parameter always comes last, because it takes everything that is left.