Coder Perfect

In JavaScript, how can I declare optional function parameters? [duplicate]


Is it possible to declare a default parameter such as

function myFunc( a, b=0)
  // b is my optional parameter

in JavaScript?

Asked by Uttam Dutta

Solution #1

This is now part of the language with ES6:

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

Please bear in mind that ES6 simply tests values for undefined, not for truthiness (so only real undefined values get the default value – falsy values like null will not default).

With ES5:

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

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

As long as all of the values you explicitly provide in are true, this will work. Null, undefined, 0, false, and ” are examples of values that are not truthy, according to MiniGod’s comment.

It’s rather usual for JavaScript libraries to perform a number of tests on optional arguments before the function begins.

Answered by Tigraine

Solution #2

This is doable with ES6 in exactly the way you’ve stated; the documentation contains a thorough discussion.

In JavaScript, default parameters can be implemented in one of two ways:

function myfunc(a, b)
    // use this if you specifically want to know if b was passed
    if (b === undefined) {
        // b was not passed
    // use this if you know that a truthy value comparison will be enough
    if (b) {
        // b was passed and has truthy value
    } else {
        // b was not passed or has falsy value
    // use this to set b to a default value (using truthy comparison)
    b = b || "default value";

If b either doesn’t exist or is false, the expression b || “default value” evaluates the value AND presence of b and returns the value of “default value.”

Alternative declaration:

function myfunc(a)
    var b;

    // use this to determine whether b was passed or not
    if (arguments.length == 1) {
        // b was not passed
    } else {
        b = arguments[1]; // take second argument

Inside the function, there is a special “array” argument that holds all of the parameters from index 0 to N – 1. (where N is the number of arguments passed).

This is sometimes used to accommodate an unknown number of optional parameters (of the same type); nonetheless, it is preferable to state the expected arguments!

Despite the fact that undefined is no longer readable in ES5, some browsers are known to ignore this. If you’re concerned about this, there are two options available to you:

b === void 0;
typeof b === 'undefined'; // also works for undeclared variables

Answered by Ja͢ck

Post is based on