Sub topic 2
Rest Parameters in Functions
This chapter assumes you can declare variables with let and const, write functions (including arrow functions), and read the array and object destructuring patterns from the previous chapter. The same ... token appears throughout. In a parameter list or pattern it collects values, which is called rest. In a call or literal it expands values, which is called spread.
Rest Parameters in Functions
A rest parameter gathers all remaining arguments into a real array. It must be the last parameter, and a function can have only one.
function sum(...nums) {
return nums.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3)); // 6
console.log(sum()); // 0 (nums is an empty array)The older arguments object is array-like, so it has no reduce method, and arrow functions don't have it at all. Use rest parameters instead.
Spreading Arrays into Literals and Calls
Spread does the reverse of rest: it expands an array into separate arguments or into elements of a new array.
const values = [3, 9, 4];
console.log(Math.max(...values)); // 9
console.log([0, ...values, 10]); // [0, 3, 9, 4, 10]Spreading Objects to Copy and Merge
Object spread copies an object's own enumerable properties into a new object literal. When two sources have the same key, the one written later wins.
const defaults = { theme: 'light', fontSize: 14 };
const settings = { ...defaults, theme: 'dark' };
console.log(settings); // { theme: 'dark', fontSize: 14 }Destructuring Function Parameters and Options Objects
You can destructure a parameter directly and give each property a default. Add = {} for the parameter as a whole, so the function still works when it is called with no argument.
function connect({ host = 'localhost', port = 5432 } = {}) {
return `${host}:${port}`;
}
console.log(connect()); // 'localhost:5432'
console.log(connect({ port: 6543 })); // 'localhost:6543'If you leave out = {}, then connect() throws a TypeError, because JavaScript can't destructure undefined.
| Position of `...` | Name | Effect |
|---|---|---|
| Function parameter list | Rest | Collects arguments into an array |
| Call arguments or array literal | Spread | Expands an iterable |
| Object literal | Spread | Copies properties |
Exercise
What does f(1, 2, 3) return, given const f = (first, ...others) => [first, others.length];?
Show answer
It returns [1, 2]. The first parameter receives 1, and the rest parameter others collects [2, 3], which has length 2.
Exercise
What happens when you call function g({ a = 1 }) { return a; } as g(), and how do you fix it?
Show answer
It throws a TypeError, because the parameter is undefined and undefined can't be destructured. To fix it, add a default for the whole parameter: function g({ a = 1 } = {}).