Functions can accept input values, known as arguments, which are assigned to parameters within the function definition. In JavaScript, functions exhibit flexibility with arguments — they can operate with fewer or more arguments than explicitly declared. Let’s delve into how this flexibility can be utilized, ranging from optional and default parameters to handling an arbitrary number of arguments.
In JavaScript, when a function is invoked with missing arguments, the unspecified parameters default to undefined
. This behavior enables the implementation of optional parameters.
To handle optional parameters more gracefully, JavaScript allows default values to be set directly in the function signature. If an argument is omitted, the default value is used instead.
You can also define multiple parameters with default values:
JavaScript functions can also be called with more arguments than the declared parameters. Extra arguments are simply ignored by the function body unless explicitly captured.
For functions that need to handle an arbitrary number of arguments, JavaScript offers the “rest parameters” syntax. This feature allows you to gather any number of trailing arguments into an array.
Closely related is the spread operator, which allows an iterable (like an array) to be expanded into individual elements where multiple arguments or elements are expected.
arguments
ObjectJavaScript functions have access to a special array-like object called arguments
that contains all the values passed to the function. This feature provides another way to handle functions called with more or fewer arguments than formally specified.