Optional Parameter in JavaScript Function

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:

  1. Do not do type checking on argument values
  2. Do not check the number of arguments passed

The following are the three ways you can call a function in JavaScript:

  1. With the exact number of arguments
  2. With more than the number of arguments specified
  3. 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:

image1.gif

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:

  1. Using If statement
  2. 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:

image2.gif

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.

image3.gif

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:

image4.gif

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:

image5.gif

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:

image6.gif

You can check the exact number of arguments as in the following and throw an exception:

image7.gif

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.

Up Next
    Ebook Download
    View all
    Learn
    View all