Yes you heard it right, C# has optional parameters in version 4.0 however it has been a part of JavaScript from the beginning of the language design.
Before reading this article, you may want to
go through the following articles:
JavaScript functions:
- Do not do type checking on argument values
- Do not check the number of arguments passed
The following are the three ways you can call a function in JavaScript:
- With the exact number of arguments
- With more than the number of arguments specified
- With fewer arguments than specified
With fewer arguments
When you call a function with fewer arguments then the remaining arguments are passed as undefined. To understand it more let us consider the following example:
When creating a function you may want to check for arguments that are not being passed and assigned a default value. The following are two ways you can assign a default value:
- Using If statement
- Using || operator
Let us assume you want to assign a default value for an optional parameter as 99. You can do that as in the following:
A better way to assign a default value is using the or operator. If the first argument is the false object in the OR operator then it will always use the second object. So when you don't pass an optional argument its values are undefined (false) and the default value will be assigned.
Always remember to put optional arguments at the end of the argument list. You cannot make the first argument an optional argument and pass the second argument. If you want to do this then you will need to explicitly pass undefined as the first parameter. So you can make the first argument optional as in the following:
With more than the number of arguments
Another possibility is that you are calling a function with more than the specified number of arguments. So for example you are calling the function above as in the following:
There is no direct way for extra arguments to be read in the function. But there is a way for extra arguments to be read. We can read extra arguments using the arguments object. So you can read extra arguments as in the following:
You can check the exact number of arguments as in the following and throw an exception:
So this is all that I have in this article to share with you on optional arguments in JavaScript functions. I hope you find this article useful. Thanks for reading.