Function Arguments and Parameters
JavaScript function definitions do not specify an expected type for the function parameters, and function invocations do not do any type checking on the argument values you pass. In fact, JavaScript function invocations do not even check the number of arguments being passed. The subsections that follow describe what happens when a function is invoked with fewer arguments than declared parameters or with more arguments than declared parameters. They also demonstrate how you can explicitly test the type of function arguments if you need to ensure that a function is not invoked with inappropriate arguments.
Optional Parameters
When a function is invoked with fewer arguments than declared
parameters, the additional parameters are set to the undefined value. It is often useful to
write functions so that some arguments are optional and may be
omitted when the function is invoked. To do this, you must be able
to assign a reasonable default value to parameters that are omitted.
Here is an example:
// Append the names of the enumerable properties of object o to the// array a, and return a. If a is omitted, create and return a new array.functiongetPropertyNames(o,/* optional */a){if(a===undefined)a=[];// If undefined, use a new arrayfor(varpropertyino)a.push(property);returna;}// This function can be invoked with 1 or 2 arguments:vara=getPropertyNames(o);// Get o's properties into a new arraygetPropertyNames(p,a);// append p's properties ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access