CodeBlanks Logo Icon CodeBlanks

Rest params

Learn to take variable arguments with rest parameters.

Rest params

A rest parameter collects a variable number of arguments into a single array. Write ... before the parameter name. The rest parameter must be an array type and must always be the last parameter.

function topla(...sayilar: number[]): number {
  let t = 0;
  for (let s of sayilar) { t += s; }
  return t;
}

With ... you can pass as many arguments as you want.

Rest parameter rules

A rest parameter must always be the last parameter in the function; it comes after other parameters. You can pass zero or more arguments. Inside the function, the rest parameter is used like a regular array.

function listele(baslik: string, ...ogeler: string[]): void {
  console.log(baslik);
  for (let o of ogeler) { console.log(o); }
}

Rest parameters let you write functions that accept a flexible number of arguments.

Practice Write a function with a rest parameter

Define a function named topla with a ...sayilar: number[] rest parameter and return type number. The function should sum all numbers with a loop and return the result. Print the result of calling topla(1, 2, 3, 4) with console.log.

Starter code

index.ts
// topla adında bir fonksiyon tanımla
// ...sayilar rest parametresi number[], dönüş türü number olsun
// tüm sayıları döngü ile topla
// topla(1, 2, 3, 4) sonucunu yazdır

Sample solution

index.ts
function topla(...sayilar: number[]): number {
    let t = 0;
    for (let s of sayilar) {
        t += s;
    }
    return t;
}
console.log(topla(1, 2, 3, 4));

Expected output

10

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does <code>...sayilar: number[]</code> do in a function parameter?

  • Gives the parameter a default value
  • Makes the parameter optional
  • Collects multiple number arguments into an array Correct answer
  • Makes the parameter readonly

Explanation: The <code>...</code> rest operator collects all passed number arguments into a single array named <code>sayilar</code>; this lets the function accept a variable number of arguments.

2 Complete the rest parameter syntax

Question
function topla(____) { let t = 0; for (let s of sayilar) { t += s; } return t; }
Answer
function topla(...sayilar: number[]) { let t = 0; for (let s of sayilar) { t += s; } return t; }

Explanation: For a rest parameter, the <code>...</code> operator is written before the parameter name; <code>sayilar: number[]</code> without the mark expects a single array argument, and <code>*</code> or trailing <code>...</code> are invalid syntax.

3 Rest params concepts

Term Meaning
...sayilar: number[] Rest parameter (variable arguments)
... (parametre önünde) Collects arguments into an array
Rest param Must be the last parameter
topla(1, 2, 3) Three arguments collected by rest parameter

All lessons in Beginner