Rest Parameters

Rest Parameters
πŸ‘¨β€πŸ’Ό Rest parameters let functions accept any number of arguments, collected into an array. This is the opposite of spreadβ€”instead of expanding, we're collecting.
function sum(...numbers: Array<number>): number {
	return numbers.reduce((a, b) => a + b, 0)
}

sum(1, 2) // 3
sum(1, 2, 3, 4, 5) // 15
The .reduce() method shown above is covered later in Exercise 6. For now, you can use a simple for loop instead:
function sum(...numbers: Array<number>): number {
	let total = 0
	for (const n of numbers) {
		total += n
	}
	return total
}

Rest vs Spread

The ... syntax means different things in different contexts:
// SPREAD - expanding into individual elements
const arr = [1, 2, 3]
console.log(...arr) // 1 2 3 (expanded)

// REST - collecting into an array
function fn(...args: Array<number>) {
	// args is an array of all passed numbers
}

Combining with Regular Parameters

Rest must be the last parameter:
function greetAll(greeting: string, ...names: Array<string>): string {
	return names.map((name) => `${greeting}, ${name}!`).join(' ')
}

greetAll('Hello', 'Alice', 'Bob', 'Charlie')
// "Hello, Alice! Hello, Bob! Hello, Charlie!"
🐨 Open
index.ts
and:
  1. Create a function using rest parameters to accept variable arguments
  2. Create a function with both regular and rest parameters
  3. Use rest in combination with spread to transform arguments
πŸ’° Rest parameters collect remaining arguments into an array.

Please set the playground first

Loading "Rest Parameters"
Loading "Rest Parameters"
Login to get access to the exclusive discord channel.
Loading Discord Posts