375

Can I declare default parameter like

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

in JavaScript?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Uttam Dutta
  • 5,250
  • 4
  • 18
  • 21

2 Answers2

639

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.

GG.
  • 21,083
  • 14
  • 84
  • 130
Tigraine
  • 23,358
  • 11
  • 65
  • 110
  • 48
    `null, undefined, 0, false, '', NaN` will all get the default value. – MiniGod Oct 09 '12 at 09:43
  • 77
    If you only want the default value if b is omitted, use `if (typeof b === 'undefined') b = 0;` – MiniGod Oct 09 '12 at 09:47
  • 2
    @MiniGod will this throw `b` into the global namespace when b is omitted? – kalu Jun 09 '15 at 20:25
  • 4
    @kalu 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. – Tigraine Jun 09 '15 at 21:19
  • 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. – Henrik Erlandsson Nov 02 '15 at 13:51
  • 7
    Why? I set the default value of 0. If you want another default value just change that to `b = b || 'foo'`. – Tigraine Nov 04 '15 at 09:58
  • 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. – user2718671 May 31 '16 at 11:19
  • @user2718671 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. – Tigraine Jun 22 '16 at 08:46
  • 1
    ```null, undefined, 0, false, '', NaN``` WONT get the default value in ES6. Only undefined would. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters – calcazar Oct 02 '17 at 20:08
  • @MiniGod would `if(typeof b==='undefined')` work the same as `if (b===undefined)`? – FistOfFury Aug 01 '19 at 19:19
  • @FistOfFury `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: https://stackoverflow.com/questions/4725603/variable-undefined-vs-typeof-variable-undefined – Richard Abey-Nesbit Oct 18 '19 at 02:23
101

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
Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309