Question 36
Question
How would you use default parameters with rest parameters in JavaScript?
Answer
Here's how to use default parameters and rest parameters together in JavaScript:
function greet(name = "World", ...greetings) {
console.log(`Hello ${name}!`);
for (const greeting of greetings) {
console.log(`${greeting}`);
}
}
greet(); // Output: Hello World!
greet("Alice", "Nice to meet you", "How are you?"); // Output: Hello Alice!
// Nice to meet you
// How are you?
greet("Bob", "Hi there"); // Output: Hello Bob!
// Hi thereExplanation:
Default Parameters: The
name = "World"part sets a default value for thenameparameter if no argument is provided.Rest Parameter: The
...greetingssyntax creates a rest parameter. This allows the function to accept any number of additional arguments, which are collected into an array calledgreetings.Function Execution:
When you call
greet()without arguments, it uses the default "World" fornameand prints nothing else (because no greetings were provided).When you provide specific values for both
nameandgreetings, they are used as expected.
Key Points:
Default parameters come before rest parameters in the function declaration.
Rest parameters must be the last parameter in a function definition.
Last updated