In javascript, you can call a function with an arbitrary number of arguments. A function can be defined with any number of arguments. If extra arguments are present, it does not matter and will be simply ignored.
function greetings(name){
console.log(`Hello ${name}!`);
}
greetings("John Doe", "Harry Potter", "Dr. Strange");
// Hello John Doe!
The above function will not give any error. But it will only use the first parameter "John Doe" and ignore the remaining ones.
Many built-in functions also support an arbitrary number of arguments. For example, Math.max() and Math.min() accepts an arbitrary number of arguments and returns the maximum and minimum of the values passed to it.
Math.max(1, 2, 4, 9, 100, 6);
// 100
Math.min(1, 2, 4, 9, 6);
// 1
The ...rest parameter
To support an arbitrary number of arguments in our function like Math.min() and Math.max() instead of ignoring them as our greetings function did in the previous example, we can use the rest parameter(...rest) to collect some or all the arguments in an array.
function greetings(...names){
for(let name of names){
console.log(`Hello ${name}!`);
}
}
greetings("John Doe", "Harry Potter", "Dr. Strange");
// Output:
// Hello John Doe!
// Hello Harry Potter!
// Hello Dr. Strange!
In the above example, "names" is the name of the array in which all the parameters are collected.
As the rest returns a pure array, you can do all the array related operations on the names array. For example,
names.length;
// 3
names.join(', ');
// John Doe, Harry Potter, Dr. Strange
Supporting fixed and variable arguments
Using the rest parameter, we can also create a function that supports fixed and variable arguments.
function greetings(greeting, ...names){
for(let name of names){
console.log(`${greeting}, ${name}!`);
}
}
greetings("How are you!", "John Doe", "Harry Potter", "Dr. Strange");
// Output:
// How are you!, John Doe!
// How are you!, Harry Potter!
// How are you!, Dr. Strange!
Rest parameter must be last
As the rest parameter collects all the remaining arguments, it must be the last argument in the list.
Correct:
function func(arg1, arg2, ...rest){};
Wrong:
function func(arg1, ...rest, arg2){};
This article was first published on hackinbits.com
Top comments (0)