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; } Commented May 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);
Sign up to request clarification or add additional context in comments.

7 Comments

@Aftershock the == has some known issues, so it's best practices to use === unless == is necessary. See stackoverflow.com/questions/359494/…
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: 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/…
What about scoping? Without keyword var, will the created values have global scope?
@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.
|
149

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 Comments

sort of...except if a===false then a=default value
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 ...
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);
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.
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.

Comments

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

Comments

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 Comments

You can also use a === undefined.
it is better to use typeof a === 'undefined' , because type coercion can take place.. 1==true is true .... 1===true is false
@jtbandes, it avoids the case where someone has done a undefined = somevalue
@GabyakaG.Petrioli Irrelevant. Who the hell would do that?
@venimus you never know the context of your code..
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 Comments

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.
I think your original answer was fine, given the explanation that null or undefined will trigger the default. Sometimes this is the desired behavior.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.