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:

  1. Default Parameters: The name = "World" part sets a default value for the name parameter if no argument is provided.

  2. 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 called greetings.

  3. Function Execution:

    • When you call greet() without arguments, it uses the default "World" for name and prints nothing else (because no greetings were provided).

    • When you provide specific values for both name and greetings, 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