JavaScript Rest Parameters - Exercise 1
It collects remaining function arguments into an array.
function logAll(...values) {
console.log(values);
}
It must be the final parameter.
function join(separator, ...parts) {
return parts.join(separator);
}
Yes. The collected values are available as a real array.
function count(...items) {
return items.length;
}
They provide named array access to all remaining arguments.
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];
}
It gathers the remaining array elements into a new array.
const [first, ...others] = ['a', 'b', 'c'];
It gathers remaining properties into a new object.
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. It becomes an empty array when no remaining arguments are supplied.
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 };
}