JavaScript Rest Parameters - Exercise 1
A rest parameter collects every argument that follows the named parameters into a new array. This gives the function a clear name for processing a flexible number of values.
function logAll(...values) {
console.log(values);
}
A rest parameter must be the final parameter because it collects all remaining arguments. A later parameter could not be assigned reliably, so function f(...rest, last) {} is invalid.
function join(separator, ...parts) {
return parts.join(separator);
}
Yes. The collected values are a real array, so properties such as length and methods such as map are available without conversion.
function count(...items) {
return items.length;
}
Rest parameters replace most uses of the older arguments object by providing named array access to the remaining arguments. Unlike arguments, the rest value is a true array.
function sum(...numbers) {
return numbers.reduce((total, value) => total + value, 0);
}
No. A parameter list can contain only one rest parameter, and it must be last.
function collect(first, ...rest) {
return [first, rest];
}
In an array pattern, rest gathers every element after the named positions into a new array. It must be the last pattern item, as in const [first, ...others] = values.
const [first, ...others] = ['a', 'b', 'c'];
In an object pattern, rest gathers the properties not already selected into a new object. The original object is not changed, so const { id, ...details } = user leaves user intact.
const { id, ...details } = user;
Rest collects multiple values; spread expands an iterable or object.
const values = [1, 2];
const copy = [...values];
const [first, ...rest] = copy;
Yes. When no remaining arguments are supplied, the rest parameter is an empty array rather than undefined. That makes checks such as items.length === 0 straightforward.
function count(...items) {
return items.length;
}
count();
They let a function accept a flexible number of arguments while keeping them easy to process.
function firstAndLast(first, ...middle) {
return { first, middle };
}