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


