Default argument values in JavaScript functions

214,919

Solution 1

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

Solution 2

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

Solution 3

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 answered before.

Solution 4

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

Solution 5

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);
}
Share:
214,919

Related videos on Youtube

Douglas Crockford
Author by

Douglas Crockford

Updated on July 24, 2020

Comments

  • Douglas Crockford
    Douglas Crockford almost 4 years

    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

    • Miguel
      Miguel about 8 years
      Simple: where "1" is the default value. function abc (arg){ arg=arg===undefined?1:arg; }
  • Trey
    Trey about 13 years
    sort of...except if a===false then a=default value
  • Boopathi Rajaa
    Boopathi Rajaa about 13 years
    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 ...
  • csiu
    csiu about 13 years
    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.
  • csiu
    csiu about 13 years
    You can also use a === undefined.
  • Trey
    Trey about 13 years
    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);
  • user113716
    user113716 about 13 years
    That's not correct. Any "falsey" value will cause the default to be set. The falsey values are NaN, undefined, null, 0, "", false.
  • user113716
    user113716 about 13 years
    I think your original answer was fine, given the explanation that null or undefined will trigger the default. Sometimes this is the desired behavior.
  • Boopathi Rajaa
    Boopathi Rajaa about 13 years
    it is better to use typeof a === 'undefined' , because type coercion can take place.. 1==true is true .... 1===true is false
  • Boopathi Rajaa
    Boopathi Rajaa about 13 years
    thanks ... edited the answer.
  • Gabriele Petrioli
    Gabriele Petrioli about 13 years
    @jtbandes, it avoids the case where someone has done a undefined = somevalue
  • Tules
    Tules over 11 years
    Boopathi this is frickin awesome, how did I not know this syntax?! Thanks so much man, this will tidy up my code a lot :D
  • jclancy
    jclancy almost 11 years
    @Aftershock the == has some known issues, so it's best practices to use === unless == is necessary. See stackoverflow.com/questions/359494/…
  • user2918201
    user2918201 almost 11 years
    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
  • Jochen van Wylick
    Jochen van Wylick over 10 years
    Very elegant - thanks!
  • T Nguyen
    T Nguyen over 10 years
    @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/…
  • Magnus
    Magnus over 10 years
    What about scoping? Without keyword var, will the created values have global scope?
  • Mark
    Mark over 10 years
    @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.
  • venimus
    venimus over 10 years
    @GabyakaG.Petrioli Irrelevant. Who the hell would do that?
  • Gabriele Petrioli
    Gabriele Petrioli over 10 years
    @venimus you never know the context of your code..
  • pedromateo
    pedromateo almost 9 years
    I think a === undefined and b === undefined is enough. This solution is more efficient and elegant. You do not need to call typeof and then to do a string comparison. Am I right?
  • Robert
    Robert over 8 years
    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.
  • DKebler
    DKebler over 7 years
    works until you have a missing options argument and need to check for a missing key like options.name. then if throws an error " Cannot read property 'name' of undefined. , cause well..options is ironically undefined. :).