231

Possible Duplicate:
How do I make a default value for a parameter to a javascript function

in PHP:

function func($a = 10, $b = 20){ // if func() is called with no arguments $a will be 10 and $ b will be 20 } 

How can you do this in JavaScript?

I get a error if I try to assign values in function arguments

missing ) after formal parameters

1
  • Simple: where "1" is the default value. function abc (arg){ arg=arg===undefined?1:arg; }
    – Miguel Q
    CommentedMay 13, 2016 at 10:30

6 Answers 6

382

In javascript you can call a function (even if it has parameters) without parameters.

So you can add default values like this:

function func(a, b){ if (typeof(a)==='undefined') a = 10; if (typeof(b)==='undefined') b = 20; //your code } 

and then you can call it like func(); to use default parameters.

Here's a test:

function func(a, b){ if (typeof(a)==='undefined') a = 10; if (typeof(b)==='undefined') b = 20; alert("A: "+a+"\nB: "+b); } //testing func(); func(80); func(100,200); 
7
  • 4
    @Aftershock the == has some known issues, so it's best practices to use === unless == is necessary. See stackoverflow.com/questions/359494/…
    – jclancy
    CommentedJul 3, 2013 at 20:30
  • 1
    Strangely, I feel like firefox was letting me define default parameters... or at least, it certainly didn't throw a syntax error. Chrome did: thanks chrome! And you you @Ravan
    – Ziggy
    CommentedJul 24, 2013 at 18:23
  • 3
    @Ziggy: As of FF 15.0, FF does indeed support default parameters. It is currently the only browser to do so but this feature is proposed for ECMAScript 6 - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
    – T Nguyen
    CommentedOct 18, 2013 at 14:15
  • 1
    What about scoping? Without keyword var, will the created values have global scope?
    – Magnus
    CommentedNov 7, 2013 at 19:49
  • 1
    @Magnus, no, because the presence of the variable in the parameter list means it's defined locally. Even if the caller omits the argument, it is defined locally as a variable of type undefined.
    – Mark
    CommentedFeb 16, 2014 at 16:15
148

ES2015 onwards:

From ES6/ES2015, we have default parameters in the language specification. So we can just do something simple like,

function A(a, b = 4, c = 5) { } 

or combined with ES2015 destructuring,

function B({c} = {c: 2}, [d, e] = [3, 4]) { } 

For detailed explanation,

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/default_parameters

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed.

Pre ES2015:

If you're going to handle values which are NOT Numbers, Strings, Boolean, NaN, or null you can simply use

(So, for Objects, Arrays and Functions that you plan never to send null, you can use)

param || DEFAULT_VALUE 

for example,

function X(a) { a = a || function() {}; } 

Though this looks simple and kinda works, this is restrictive and can be an anti-pattern because || operates on all falsy values ("", null, NaN, false, 0) too - which makes this method impossible to assign a param the falsy value passed as the argument.

So, in order to handle only undefined values explicitly, the preferred approach would be,

function C(a, b) { a = typeof a === 'undefined' ? DEFAULT_VALUE_A : a; b = typeof b === 'undefined' ? DEFAULT_VALUE_B : b; } 
4
  • 13
    sort of...except if a===false then a=default value
    – Trey
    CommentedJun 26, 2011 at 19:54
  • the default value is only used when the argument is not set... not when it is set to false .... that is a wrong way of manipulation .... undefined, null, and false .. these three are different ...CommentedJun 26, 2011 at 19:57
  • 1
    if the variable you are testing is false, then this statement will treat it like it's undefined or null.: function testMe(a,b){ alert(a || 'fail'); } testMe(false);
    – Trey
    CommentedJun 26, 2011 at 19:59
  • Warning! This is one of the most common bugs in JavaScript and should most of the time be avoided. As already mentioned, this will not work as you might expect for strings, ints or booleans.
    – Robert
    CommentedDec 7, 2015 at 21:27
12

You have to check if the argument is undefined:

function func(a, b) { if (a === undefined) a = "default value"; if (b === undefined) b = "default value"; } 

Also note that this question has been answeredbefore.

    5

    I have never seen it done that way in JavaScript. If you want a function with optional parameters that get assigned default values if the parameters are omitted, here's a way to do it:

     function(a, b) { if (typeof a == "undefined") { a = 10; } if (typeof b == "undefined") { a = 20; } alert("a: " + a + " b: " + b); } 
      4
      function func(a, b) { if (typeof a == 'undefined') a = 10; if (typeof b == 'undefined') b = 20; // do what you want ... for example alert(a + ',' + b); } 

      in shorthand

      function func(a, b) { a = (typeof a == 'undefined')?10:a; b = (typeof b == 'undefined')?20:b; // do what you want ... for example alert(a + ',' + b); } 
      5
      • 5
        You can also use a === undefined.
        – jtbandes
        CommentedJun 26, 2011 at 19:59
      • it is better to use typeof a === 'undefined' , because type coercion can take place.. 1==true is true .... 1===true is falseCommentedJun 26, 2011 at 20:15
      • 2
        @jtbandes, it avoids the case where someone has done a undefined = somevalueCommentedJun 26, 2011 at 22:44
      • 1
        @GabyakaG.Petrioli Irrelevant. Who the hell would do that?
        – venimus
        CommentedFeb 27, 2014 at 17:31
      • @venimus you never know the context of your code..CommentedFeb 27, 2014 at 17:53
      0

      You cannot add default values for function parameters. But you can do this:

      function tester(paramA, paramB){ if (typeof paramA == "undefined"){ paramA = defaultValue; } if (typeof paramB == "undefined"){ paramB = defaultValue; } } 
      2
      • This isn't the best way to do it because if a parameter isn't passed then it's actually undefined. It just happens that undefined == null returns true.
        – jtbandes
        CommentedJun 26, 2011 at 19:59
      • 1
        I think your original answer was fine, given the explanation that null or undefined will trigger the default. Sometimes this is the desired behavior.CommentedJun 26, 2011 at 20:08

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.