Skip to content

JavaScript optional parameters | Example code

  • by

JavaScript Optional Parameter allows for passing less number of fewer parameters to a function and assigning a default value. These parameters 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

A simple example code initializes named parameters with default values whenever no value or undefined is passed.

<!DOCTYPE html>
<html>
<body>
  <script>

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

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

  </script>
</body>
</html> 

Output:

JavaScript optional parameters

More example

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

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

Note: default parameter values are evaluated at the time the function is called, not when it’s defined. This means you can use expressions as default values, and the expressions will be evaluated each time the function is called without the corresponding argument.

function multiply(a, b = 2 * a) {
  return a * b;
}

console.log(multiply(5)); // Output: 5 * 2 * 1 = 10
console.log(multiply(5, 3)); // Output: 5 * 3 = 15

In the multiply function, the default value for b is 2 * a, so if b is not provided when the function is called, it will default to twice the value of a.

Setting second optional parameter JavaScript

The best method is to define the parameters in the right order, so the last ones are the options, 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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading