Advantage of function
These are the main advantages of functions.
There are three aspects of a function.
We can create a function in two ways. These are:
When we declare and call a function by its given name, then this type of function is known as a named function.
A function without a name is known as an anonymous function. These type of functions are dynamically declared at runtime. It is defined as an expression. We can store it in a variable, so it does not need function names. Like standard function, it also accepts inputs and returns outputs. We can invoke it by using the variable name, which contains function.
Parameters are the values or arguments that passed to a function. In TypeScript, the compiler accepts the same number and type of arguments as defined in the function signature. If the compiler does not match the same parameter as in the function signature, then it will give the compilation error.
Function parameter can be categories into the following:
TypeScript provides an option to set default values to the function parameters. If the user does not pass a value to an argument, TypeScript initializes the default value for the parameter. The behavior of the default parameter is the same as an optional parameter. For the default parameter, if a value is not passed in a function call, then the default parameter must follow the required parameters in the function signature. However, if a function signature has a default parameter before a required parameter, we can still call a function which marks the default parameter is passed as an undefined value.
Note: We cannot make the parameter optional and default at the same time.
The rest parameter is used to pass zero or more values to a function. We can declare it by prefixing the three "dot" characters ('...') before the parameter. It allows the functions to have a different number of arguments without using the arguments object. The TypeScript compiler will create an array of arguments with the rest parameter so that all array methods can work with the rest parameter. The rest parameter is useful, where we have an undetermined number of parameters.
Rules to follow in rest parameter: