Explore essential concepts of default function parameters and rest arguments with this quiz, designed to reinforce understanding of argument handling in modern programming. Strengthen your skills with practical scenarios and nuanced options focused on default values and flexible input handling.
In a function definition with default parameters, such as function greet(name = 'Guest'), what will greet() return if called without any arguments?
Explanation: When a function is called without passing an argument for a parameter with a default value, the default value is used, so greet() returns 'Guest'. It does not result in an error because the default handles the missing argument. Returning undefined or requiring at least one input does not align with how default parameters work, making those options incorrect.
Given the function displayInfo(age, name = 'Unknown'), what happens if displayInfo(25) is called?
Explanation: The first argument passed assigns to the first parameter, so age is 25, and since no second argument is provided, name uses the default 'Unknown'. Switching age and name or skipping parameters does not fit parameter assignment rules. There is also no syntax error in this valid usage.
If a function is declared as function sum(...numbers), how does it process function calls with multiple numbers such as sum(1, 2, 3)?
Explanation: The rest parameter syntax allows the function to gather all provided arguments into an array, letting you process an arbitrary number of values. Only taking two arguments or converting to a string is incorrect. No error is raised for multiple arguments used with rest parameters.
In the declaration function concat(separator, ...strings), what does concat('-', 'a', 'b', 'c') produce?
Explanation: The first argument is assigned to separator, and all subsequent arguments are placed in the strings array, so joining these produces 'a-b-c'. Throwing an exception or treating all arguments as one string is incorrect. The separator is not included among the joined strings themselves.
Given function multiply(a, b = 2), what is the result of multiply(5, undefined)?
Explanation: Passing undefined as a function argument triggers the use of the default parameter, so b becomes 2 and the function returns 10. Returning undefined or 5 does not follow default parameter behavior, and no error is thrown in this scenario.