rest parameter syntax Flashcards
What is the rest parameter syntax?
The rest parameter syntax allows a function to accept an indefinite number of arguments, providing a way to represent variadic functions in JavaScript.
function sum(…theArgs) {
let total = 0;
for (const arg of theArgs) {
total += arg;
}
return total;
}
console.log(sum(1, 2, 3));
// Expected output: 6
console.log(sum(1, 2, 3, 4));
// Expected output: 10
What is a variadic function?
A function which accepts a variable number of arguments.
What will the output be for this code
function myFun(a, b, …manyMoreArgs) {
console.log(“a”, a);
console.log(“b”, b);
console.log(“manyMoreArgs”, manyMoreArgs);
}
myFun(“one”, “two”, “three”, “four”, “five”, “six”);
// Console Output:
// a, one
// b, two
// manyMoreArgs, [“three”, “four”, “five”, “six”]
Is the following function declaration correct?
function myFunc2(…myArgs, …myOtherArgs, arg2, arg3) {
// the function body
}
No there can only be one rest parameter (here we have two …myArgs and …myOtherArgs) and the rest parameter needs to go last in the parameter list.
Correct version
function myFunc2( arg1, arg2, …myArgs) {
// the function body
}
How is it best to think about the naming of the rest parameter syntax?
It is named rest parameter because it an array that contains the rest of the arguments passed to a function.
function myFunc(arg1, arg2, …myArgs) {
// the function body
console.log(“arg1”, arg1);
console.log(“arg2”, arg2);
console.log(“myArgs”, myArgs);
}
myFunc(
“1”,
“2”,
“These”,
“are”,
“the”,
“rest”,
“of”,
“the”,
“parameters”,
“provided”,
“to”,
“this”,
“function”
);
// output
arg1 1
arg2 2
myArgs [‘These’, ‘are’, ‘the’, ‘rest’, ‘of’, ‘the’, ‘parameters’, ‘provided’, ‘to’, ‘this’, ‘function’]
In general usage which is better, the arguments object or the rest parameter syntax?
The rest parameter syntax is better, it creates an actual array so array methods can be used on it. The arguments object is not an actual array and it has other issues so it is best avoided.