JavaScript function optional parameter | 3 Ways Examples code

You can declare a function with optional parameter using Logical OR operator (‘||’) or Assignment operator (“=”), etc in JavaScript.

JavaScript function optional parameter can do it in 3 ways:-

  • Undefined property
  • OR (||) operator
  • The assignment operator (“=”)

Declare optional function parameters in JavaScript Example

Let’s see all method examples in HTML:-

Using undefined property

Undefined property indicates that a value is not assigned to a variable.

Output:

JavaScript function optional parameter Undefined

OR (||) operator

In the example the optional parameter is ‘b’:

The optional parameter is Logically OR with the default value within the body of the function and should always come at the end of the parameter list.

Pre ES2015,

Output:

JavaScript function optional parameter OR operator

The assignment operator (“=”)

The optional variable is assigned the default value in the declaration statement itself and should end on the parameter list.

From ES6/ES2015, default parameters are in the language specification.

Output:

1 2
10 0

Do comment if you have any doubts and suggestion on this JS function topic.

Note: All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.