But what happens if a smaller number of arguments are passed to it when the function is called, than its parameters are set? Let’s get a look:
The rule here is simple: parameters that do not have an argument are automatically initialized with a value
undefined. We illustrate this in more detail using the example of a function that takes three parameters as input and prints their values:
There are situations when it is not known in advance whether the argument will be passed at all during the execution of the function code, or whether the argument passed will contain a meaningful value (other than the value of
undefined). In such cases, it is convenient to provide some default value for the parameter.
Suppose we want that when calling the
greeting function without parameters, it displays the message
Hi, anonymous! .
Then we can implement it as follows:
It works as follows. If the parameter is not passed, then the default value is substituted (that to the right of the operator
=). If the parameter is passed, then no reassignment occurs. The parameter will be equal to the value that was actually passed to the function.
In addition, identifiers can be used in default values:
But do not abuse this method. Default values are not always suitable for full programming.
You may be wondering what will happen if you call a function with larger number of parameters?
Answer: nothing happens, they will simply be ignored.