What is the most efficient method for setting default parameter values ​​in javascript?

I know two methods for setting a default parameter, but I would like to know which method is preferred.

function Foo(par1, par2)
{
    if(par2 == null)
        par2 = "my default"
}

or

function Foo(par1, par2)
{
    par2 = par2 || "my default"
}

or is there a better way than any of these?

EDIT:

I would also like to know how others handle several optional parameters, such as: We have several functions like this in internal libraries (I think they are pretty ugly).

function Foo(par1, par2, par3)
{
    if(par2 == null)
        par2 = "my default"
    if(par3 == null)
        par3 = "my default"
    // Do something
}

And to call him:

Foo("Parameter one",null,true)
+3
source share
11 answers

, , , , , sergey, , args, arg.

.

function Foo(myArgs)
{
    myArgs.par1 = myArgs.par1 || "my default"
    myArgs.par2 = myArgs.par2 || "my default"
}
+2

, undefined, null.

par2 !== null true .

javascript, , null, undefined, false , undefined.

if (par2 !== undefined)
        par2 = "my default";

    par2 = par2 !== undefined ? par2 : "my default";

, false null.

, , , false null.

+5

:

1) (, undefined null, DOM insertBefore), , :

function Foo(par1, par2)
{
    if (arguments.length < 2)
        par2 = "my default"
    else
    if (arguments.length < 3)
        par3 = "my default"
}

2) , undefined, :

function Foo(par1, par2)
{
    if (arguments.length < 2 && par2 === undefined)
        par2 = "my default"
    else
    if (arguments.length < 3 && par3 === undefined)
        par3 = "my default"

}

3) , null, :

function Foo(par1, par2)
{
    if (arguments.length < 2 && (par2 === undefined || par2 === null))
        par2 = "my default"
    else
    if (arguments.length < 3 && (par3 === undefined || par3 === null))
        par4 = "my default"
}

: , .

+4

, .

+3

:

function myFunc(arg1, arg2, arg3) {
    switch (arguments.length) {
        case 0 : arg1 = "default1";
        case 1 : arg2 = "default2";
        case 2 : arg3 = "default3";
    }
}
+2

.

+1

, , .

, , par2 false, 0, , null undefined:

par2 = par2 || 'default value';

, .

+1

, , . :

function Foo(par1, par2)
{
    par2 = par2 ? par2 : 'default value';
}

, , , , .

0

jquery, :

function foo(params){
 var params = $.extend({}, {bar: '2'}, params);
 alert(params.bar);
}
foo(); //Alerts 2
0

The only thing you need to think about when using the solution.

var foo = bar || 123;

is that the value of bar, which evaluates to false. This may cause problems in the future.

Eric

0
source

If you pass a lot of arguments to a function, you can do something like:

function myFunc() {
    arguments[0] = arguments[0] || "default value for first argument";
    arguments[3] = arguments[3] || "default value for fourth argument";
    alert(arguments[3]);
}
0
source

All Articles