rest parameter syntax Flashcards

1
Q

What is the rest parameter syntax?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is a variadic function?

A

A function which accepts a variable number of arguments.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

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”);

A

// Console Output:
// a, one
// b, two
// manyMoreArgs, [“three”, “four”, “five”, “six”]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Is the following function declaration correct?

function myFunc2(…myArgs, …myOtherArgs, arg2, arg3) {
// the function body
}

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How is it best to think about the naming of the rest parameter syntax?

A

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’]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

In general usage which is better, the arguments object or the rest parameter syntax?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly