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 there
Explanation:
Default Parameters: The
name = "World"
part sets a default value for thename
parameter if no argument is provided.Rest Parameter: The
...greetings
syntax 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" forname
and prints nothing else (because no greetings were provided).When you provide specific values for both
name
andgreetings
, 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