How can I declare optional function parameters in JavaScript? [duplicate]
Asked Answered
S

2

378

Can I declare default parameter like

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

in JavaScript?

Supralapsarian answered 9/10, 2012 at 9:41 Comment(0)
A
646

With ES6: This is now part of the language:

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

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).


With ES5:

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

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

This works as long as all values you explicitly pass in are truthy. Values that are not truthy as per MiniGod's comment: null, undefined, 0, false, ''

It's pretty common to see JavaScript libraries to do a bunch of checks on optional inputs before the function actually starts.

Ankh answered 9/10, 2012 at 9:42 Comment(11)
null, undefined, 0, false, '', NaN will all get the default value.Skees
If you only want the default value if b is omitted, use if (typeof b === 'undefined') b = 0;Skees
@Skees will this throw b into the global namespace when b is omitted?Orientalize
@Orientalize no because you have defined it in the local scope (the function). It is declared and scoped at the function level but will be undefined if not called from outside. So no global scope assignment happens here.Ankh
Not a generally useful answer since you usually want to supply default values for your optional parameters. The answer is correct only for functions where all optional parameters are to have the default value of 0.Northnortheast
Why? I set the default value of 0. If you want another default value just change that to b = b || 'foo'.Ankh
Thanks, works just fine. But with JSHint following warning messages occure: when using the update version - 'default parameters' is only available in ES6 (use 'esversion: 6'). - and this when using your first solution: 'variable_name' is already defined.Musaceous
@Musaceous That's a setting for JSHint, obviously ES6 syntax is invalid syntax in ES5 so you have to tell JSHint which version you are targetting so it can output meaningful errors. As for the second: yes that's something JSHint will report on as it is bad practice in JS to reuse variables, in this case we are doing it for good reasons. Also please keep in mind that JSHint is just a style and syntax checker for JS. Many of the rules it has are stylistic in nature (the community decided that in 99% of cases we don't want you doing X), and sometimes you need to break these rules.Ankh
null, undefined, 0, false, '', NaN WONT get the default value in ES6. Only undefined would. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Erlond
@Skees would if(typeof b==='undefined') work the same as if (b===undefined)?Tseng
@Tseng typeof b==='undefined' is generally more robust than b===undefined. b===undefined will not work as expected if undefined is redefined - this should never be done but it is possible to do in some browsers. And while it's not relevant to this example because we're declaring b in our function definition, in the general case typeof b==='undefined' will also work without throwing an error in the event that b were not defined. See this thread for more details: #4726103Aphelion
V
103

Update

With ES6, this is possible in exactly the manner you have described; a detailed description can be found in the documentation.

Old answer

Default parameters in JavaScript can be implemented in mainly 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";
}

The expression b || "default value" evaluates the value AND existence of b and returns the value of "default value" if b either doesn't exist or is falsy.

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
    }
}

The special "array" arguments is available inside the function; it contains all the arguments, starting from index 0 to N - 1 (where N is the number of arguments passed).

This is typically used to support an unknown number of optional parameters (of the same type); however, stating the expected arguments is preferred!

Further considerations

Although undefined is not writable since ES5, some browsers are known to not enforce this. There are two alternatives you could use if you're worried about this:

b === void 0;
typeof b === 'undefined'; // also works for undeclared variables
Villainous answered 9/10, 2012 at 9:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.