Rest parameters vs the arguments object in JavaScript
Intermediate · 3 min read
Some functions don't know in advance how many arguments they will get. Math.max(3, 9, 4) takes any number of numbers. A total function for a shopping basket should accept two amounts or twenty. JavaScript has a neat way to write this: the rest parameter, written with three dots, ...amounts.
In this tutorial you will write total(...amounts), which adds up any number of amounts, and receipt(customer, ...items), which takes a name first and then the items. You will also meet spread, the same three dots used the other way round, and the old arguments object that rest replaced. You need to know how to write a function and what an array is.
Rest gathers arguments into an array
Put ... before the last parameter, and every argument from that point on is collected into a real array:
function show(...things) {
return things;
}
console.log(show(1, 2, 3)); // [ 1, 2, 3 ]
console.log(show()); // []
With no arguments, you get an empty array, never undefined. Because it is an array, reduce, map, filter and everything else work on it.
Spread does the opposite
At a call site, ... does the reverse: it takes an array apart into separate arguments. total(...[1, 2, 3]) is the same as total(1, 2, 3). Same three dots, opposite direction. In a parameter list they gather. In a call they spread.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
90 Rest parameters, and the old arguments object
fairTotal any number of amounts passed as separate arguments. Then split a receipt's first argument from the rest, and compare what ...rest gives you with the old arguments object.
Stuck? Three hints, smallest first
- 1.
...restmust be the last parameter, and it gathers what is left into a real array. - 2. Spread at the call site does the opposite:
total(...list). - 3.
argumentsis array-like, so it has a length and no array methods.
Step 1: total any number of amounts
Amounts are in kobo (100 kobo make one naira). The underscores in 200_00 only make the number easier to read.
function total(...amounts) {
return amounts.reduce((sum, kobo) => sum + kobo, 0);
}
console.log(total(200_00, 350_00, 150_00)); // 70000
console.log(total()); // 0
amounts is an array of everything passed in. reduce adds them up, starting from 0, so an empty call gives 0 instead of an error.
Step 2: named parameters first
A rest parameter must come last, but you can put named ones before it. The receipt takes the customer's name, then any number of items:
function total(...amounts) {
return amounts.reduce((sum, kobo) => sum + kobo, 0);
}
function receipt(customer, ...items) {
return customer + ' owes ' + total(...items);
}
console.log(receipt('Adaeze', 200_00, 350_00)); // Adaeze owes 55000
customer gets the first argument. items gets the rest: [20000, 35000]. Then total(...items) spreads that array back out into separate arguments for total.
Step 3: spread an array you already have
Often the amounts are already in an array. Passing the array itself would be wrong. Spread it:
function total(...amounts) {
return amounts.reduce((sum, kobo) => sum + kobo, 0);
}
const fares = [200_00, 350_00, 500_00];
console.log(total(...fares)); // 105000
console.log(total(fares)); // 020000,35000,50000
Without the dots, total gets one argument, the whole array, so amounts is [[20000, 35000, 50000]]. Then 0 + [array] turns the array into text and joins it on, which is how you end up with that strange 020000,35000,50000. No error, just a wrong answer.
Step 4: the old way, arguments
Before rest parameters existed, a function read its extra arguments from a special object called arguments. You will still see it in older code:
function oldStyle() {
console.log(arguments.length); // 2
console.log(arguments[0]); // 1
console.log(Array.isArray(arguments)); // false
try {
arguments.map((n) => n);
} catch (err) {
console.log(err.name); // TypeError
}
}
oldStyle(1, 2);
arguments has numbered entries and a length, so it looks like an array. It is array-like, but not an array: it has none of the array methods, so arguments.map throws. It also doesn't exist in its own right inside an arrow function. Rest parameters fix all of that, and say in the function's first line what it accepts.
Step 5: length ignores rest
A function's length counts its named parameters only:
function total(...amounts) {
return amounts.reduce((sum, kobo) => sum + kobo, 0);
}
function receipt(customer, ...items) {
return customer + ' owes ' + total(...items);
}
console.log(total.length); // 0
console.log(receipt.length); // 1
total accepts anything you give it, yet its length is 0. Don't rely on length to know how many arguments a function takes.
The full solution
The answer panel has total, receipt and the old-style function, spreads the fares back in, and checks the rest array, the empty call, both length values and the TypeError from arguments.map. Press Run to see the output.
function total(...amounts) {
return amounts.reduce((sum, kobo) => sum + kobo, 0);
}
function receipt(customer, ...items) {
return customer + ' owes ' + total(...items);
}
function isRealArray(...rest) {
return Array.isArray(rest);
}
// The pre-2015 way. arguments exists inside a function declaration, is not an
// array, and does not exist at all inside an arrow function.
function oldStyle() {
const looksLikeArray = Array.isArray(arguments);
let mapped = 'threw';
try {
mapped = arguments.map((n) => n);
} catch {
// arguments has no map
}
return { count: arguments.length, looksLikeArray, mapped };
}
const fares = [200_00, 350_00, 500_00];
console.log('spread back in:', total(...fares));
console.log('arguments:', oldStyle(1, 2));
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('rest gathers everything into one array', total(200_00, 350_00, 150_00), 70000);
test('and it is a real array, so reduce works on it', isRealArray(1, 2), true);
test('no arguments at all is fine', total(), 0);
test('length ignores a rest parameter', total.length, 0);
test('named parameters before it still count', receipt.length, 1);
test('spread sends an array back in as separate arguments', total(...fares), 105000);
test('a receipt splits the first argument from the rest', receipt('Adaeze', 200_00, 350_00), 'Adaeze owes 55000');
test('the old arguments object is not an array', oldStyle(1, 2).looksLikeArray, false);
test('so calling map on it throws', oldStyle(1, 2).mapped, 'threw');
...rest in a parameter list gathers; ... at a call site spreads. Same three dots, opposite directions, and the pair replaces every use of arguments: rest is a genuine array, so reduce, map and filter are all available, and it can sit after named parameters as in receipt.
arguments is array-like — indices and a length, nothing else — so arguments.map(...) throws a TypeError rather than doing anything useful. It also does not exist inside an arrow function, which inherits it from the enclosing function along with this. The one thing to watch is length: it counts named parameters only, so total.length is 0 despite total accepting anything you throw at it.
Common mistakes
- Putting the rest parameter anywhere but last.
function f(...a, b)is a syntax error. - Passing an array without spreading it.
total(fares)gets one argument. Writetotal(...fares). - Calling array methods on
arguments. It is only array-like. Use a rest parameter, orArray.from(arguments).
Try it yourself
- Write
largest(...numbers)usingMath.max(...numbers). What does it return with no arguments? - Change
receiptso it also lists the count:Adaeze owes 55000 for 2 items. - Write
average(...marks)that returns0for no marks instead ofNaN.