TypeScript
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.
Exercise 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.
Show example solution
function topla(...sayilar: number[]): number {
let t = 0;
for (let s of sayilar) {
t += s;
}
return t;
}
console.log(topla(1, 2, 3, 4));
Test yourself
-
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
- Makes the parameter readonly
Show answer
Collects multiple number arguments into an array — 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.
-
Complete the rest parameter syntax
function topla(____) { let t = 0; for (let s of sayilar) { t += s; } return t; }
Show answer
function topla(...sayilar: number[]) { let t = 0; for (let s of sayilar) { t += s; } return t; }
-
Rest params concepts
- ...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
Next lesson: Function overloads