JavaScript gives you three ways to handle a variable number of arguments. There is a default parameter for the ones that may be missing, there is a rest parameter for the ones that have no names, and there is the spread operator to pass an array in as separate arguments. Together they replace almost every use of the old arguments object, and they make the signature of a function much easier to read.
The previous lesson in this module covered "Arrow Functions vs Regular Functions", and the next lesson in this module is about "Scope and a First Look at Closures".
How do default parameters work?
Put an = and a value after a parameter, and that value is used whenever the caller does not supply one.
function greet(name, greeting = 'Hello') {
return greeting + ', ' + name + '!';
}
console.log('one argument gives', greet('Ada'));
console.log('two arguments give', greet('Ada', 'Good morning'));
console.log('an extra argument is ignored:', greet('Ada', 'Hi', 'extra'));
console.log('the length of greet is', greet.length);
The last line surprises people. The length property of a function counts the parameters that come before the first one with a default, so a function whose very first parameter has a default reports a length of zero. It is a quirk of the language and not something to rely on, but you will meet it if you ever write code that inspects how many arguments a function takes.
What does a default NOT replace?
A default only kicks in when the argument is undefined. Every other value, including null, 0, and the empty string, is used exactly as it was given.
function handle(value, fallback = 'default') {
return value + ' / ' + fallback;
}
console.log('nothing given:', handle('given'));
console.log('null is kept:', handle('given', null));
console.log('an empty string is kept:', handle('given', ''));
console.log('zero is kept:', handle('given', 0));
This is the behaviour that you want, and it is a deliberate decision in the language. The call handle('given', null) means that the caller explicitly said "there is no fallback", and that is different from the caller forgetting to pass a value at all. The function can tell those two situations apart.
There are two related rules that are worth knowing. A default expression is evaluated when the function is called and not when it is defined, so it can depend on the other parameters. And a parameter that refers to a later parameter in its default runs into the temporary dead zone, because the later binding has not been given its value yet.
function scaled(size, factor = size * 2) {
return size * factor;
}
console.log('scaled(5) gives', scaled(5));
What is the rest parameter?
Three dots in front of a parameter name collect every remaining argument into a real array.
function sum(...numbers) {
let total = 0;
for (const number of numbers) {
total = total + number;
}
return total;
}
console.log('three numbers give', sum(1, 2, 3));
console.log('one number gives', sum(10));
console.log('no numbers give', sum());
Three properties make it better than arguments. It is a genuine array, so map, filter, and reduce all work on it. It is scoped to that one function, so it does not leak out of it. And it appears in the signature of the function, which tells a reader that the function accepts any number of arguments.
Can I mix named parameters and a rest parameter?
Yes, and the rest parameter has to come last. The named parameters take the first positions, and the rest parameter collects whatever is left over.
function label(name, ...tags) {
return name + ' [' + tags.join(', ') + ']';
}
console.log('no tags:', label('post'));
console.log('two tags:', label('post', 'js', 'web'));
console.log('three tags:', label('post', 'js', 'web', '2026'));
This is the shape that you want for a function whose first argument is special and whose other arguments form a list. A formatter that takes a template name and a set of values is one example, and so is a logger that takes a channel and a set of messages, or a query builder that takes a table and a set of conditions.
What is the arguments object, and why should you avoid it?
Every regular function has an arguments object that lists what it was called with. It comes from before the rest parameter existed, and it is still everywhere in older code.
function countArgs() {
return arguments.length;
}
function countArgsRest(...args) {
return args.length;
}
function hasMap() {
return typeof arguments.map;
}
console.log('arguments gives', countArgs(1, 2, 3));
console.log('rest gives', countArgsRest(1, 2, 3));
console.log('no arguments gives', countArgs());
console.log('arguments has a map method:', hasMap(1, 2));
The last line is the practical problem. arguments has a length and numeric indexes, but it is not an array, so arguments.map does not exist. The rest parameter gives you the same information as a proper array, so there is no reason to reach for arguments in new code.
How do I pass an array as a list of arguments?
With the spread operator, which is written ..., in the call position. It expands an array into separate arguments.
function total(a, b, c) {
return a + b + c;
}
const parts = [10, 20, 30];
console.log('spreading fills the slots:', total(...parts));
function logAll(...values) {
console.log('the rest parameter holds', values);
}
logAll(...parts);
Spreading three values into a function that takes three parameters fills all three slots, so anything extra goes nowhere. Spreading does not append to the list of parameters. It fills it from the left.
Spread and rest are the same three dots doing opposite jobs. In a list of parameters, ... collects the arguments into an array. In a list of arguments, ... expands an array into arguments. Once that clicks, the two of them read as a pair instead of two separate tricks.
What are the common rest and spread mistakes?
There are three that come up constantly, and one of them surprises people the first time they see it.
console.log('spreading a string:', [...'abc']);
console.log('a plain array:', ['abc']);
console.log('spreading a set:', [...new Set([1, 1, 2])]);
console.log('mixing is allowed:', [...'ab', 'c']);
The first line is the surprise. Spreading a string produces its characters and not the string itself. If you wanted an array with a single item in it, then [...'abc'] is not the way to write it. You would put the string inside brackets first.
The second mistake is placement. A rest parameter has to be the last one in the list. The code function collect(first, ...rest, last) is a syntax error, because there would be no sensible way to decide where the rest ends and the named parameter begins.
The third mistake is getting the direction wrong. Rest collects into an array, and spread expands from an array. Read the three dots as an arrow in each case. ...args means "the arguments become args", and fn(...args) means "args become the arguments".
The parameter tricks worth remembering
- A default parameter applies only when the argument is
undefined, and not fornull,0, or''. - Defaults are evaluated at call time, so they can use the parameters that come before them.
...restcollects the remaining arguments into a real array, and it has to be the last parameter.- Mix named parameters with a rest parameter when the first argument is special and the rest form a list.
- Prefer a rest parameter over the
argumentsobject, because it is a real array and it shows up in the signature. ...spreadin a call expands an array into individual arguments, filling the parameters from the left.
Try it yourself: write a function logAll(...messages) that prints each message on its own line, and a function joinAll(separator, ...parts) that joins the remaining parts with the separator. Test both of them with zero arguments, with one argument, and with several arguments. Then write a version of joinAll that takes an array instead, and use spread to feed that array into your original function, so that you have both forms without duplicating any logic.