Skip to content

JavaScript optional parameters | Example code

  • by

JavaScript Optional Parameter is allow to pass less number of parameters to a function and assign a default value. These parameters that need not always be passed i.e. they’re optional.

With ES6:

Please keep in mind that ES6 checks the values against undefined and not against truthy-ness (so only real undefined values get the default value – falsy values like null will not default).

function myFunc(a, b = 0) {
   // function body

Generally, if you don’t pass parameters, ‘undefined‘ is passed instead. But using Optional Parameters, you can define a default value. So, whenever no value or undefined is passed, a default value is passed in its place.

With ES5:

function myFunc(a,b) {
  b = b || 0;

  // b will be set either to b or to 0.

JavaScript optional parameters

Simple example code initialize named parameters with default values whenever no value or undefined is passed.

<!DOCTYPE html>

    function add(a, b = 1) {
      return a + b;

    console.log(add(100, 200));



JavaScript optional parameters

More example

function multiply(a, b) {
  return a * b

multiply(5, 2)  // 10
multiply(5)     // NaN !

Setting second optional parameter JavaScript

The best method is to define the parameters in the right order, so the last ones are the optionals, and then you will be able to use the optional arguments as defined in ES6

function(c, a=1, b=2) {
   // ...

Since named parameters are not supported in JS, if you have many optional parameters, replace them by a single object.

function(obj) {
   // obj.a, obj.b, obj.c

Alternatively you could use the arguments object in the function body.

function() {
    // arguments[0], arguments[1], arguments[2]

If you are not able to redesign the function, then find out the default values for the parameters, and use those. It is usually 0, an empty array or null.

Do comment if you have any doubts or suggestions on this JS parameter topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *