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 joinWords(...words: Array<string>): string {
	return words.join(' ')
}

joinWords('hello', 'world') // "hello world"
If you need to walk every rest argument before we cover .reduce() in Exercise 5, a simple for...of loop works well:
function longestWord(...words: Array<string>): number {
	let maxLength = 0
	for (const word of words) {
		if (word.length > maxLength) {
			maxLength = word.length
		}
	}
	return maxLength
}

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 multiply(...numbers) that returns the product of all arguments. Edge cases: one number returns that number; no arguments returns 1
  2. Create logWithPrefix(prefix, ...messages) that logs each message with the prefix (practice only β€” not graded)
  3. Create sum(...numbers) that returns the sum of all arguments. Edge cases: one number returns that number; no arguments returns 0
  4. Create mergeArrays(...arrays) that merges any number of number arrays into one array (in argument order). With no arguments, return []
  5. Export the graded functions: multiply, sum, and mergeArrays
πŸ’° Rest parameters collect remaining arguments into an array.

Please set the playground first

Loading "Rest Parameters"
Loading "Rest Parameters"