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

Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184
Douglas Crockford
  • 2,325
  • 2
  • 14
  • 4

6 Answers6

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);
Xesau
  • 161
  • 1
  • 9
Ravan Scafi
  • 6,382
  • 2
  • 24
  • 32
  • 4
    @Aftershock the `==` has some known issues, so it's best practices to use `===` unless `==` is necessary. See http://stackoverflow.com/questions/359494/javascript-vs-does-it-matter-which-equal-operator-i-use – jclancy Jul 03 '13 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 Jul 24 '13 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 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/default_parameters – T Nguyen Oct 18 '13 at 14:15
  • 1
    What about scoping? Without keyword var, will the created values have global scope? – Magnus Nov 07 '13 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 Feb 16 '14 at 16:15
  • 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? – pedromateo Jul 16 '15 at 11:01
  • 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. :). – DKebler Oct 30 '16 at 09:02
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;
}
Boopathi Rajaa
  • 4,659
  • 2
  • 31
  • 53
  • 13
    sort of...except if a===false then a=default value – Trey Jun 26 '11 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 ... – Boopathi Rajaa Jun 26 '11 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 Jun 26 '11 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 Dec 07 '15 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 answered before.

Community
  • 1
  • 1
jtbandes
  • 115,675
  • 35
  • 233
  • 266
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);
    }
tkahn
  • 1,407
  • 2
  • 21
  • 37
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);
}
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
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;
 }
}
evilone
  • 22,410
  • 7
  • 80
  • 107
  • 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 Jun 26 '11 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. – user113716 Jun 26 '11 at 20:08