Default values of parametrs for own functions in jquery

14,001

Solution 1

One way to do this is to check the parameters. For example:

function test(paramA) {
    if (paramA == null) {
        paramA = defaultValue;
    }
    // use paramA here
}

Another possibility is this:

function test() {
    var paramA = defaultValue;
    if (arguments.length == 1) {
        paramA = arguments[0];
    }
    // use paramA here
}

Solution 2

i can't vote right now but agree with color2life.

a = a || "something"

is probably the most concise and readable version.

Solution 3

You might want to check for undefined instead of null.

var f=function(param){
  if(param===undefined){
    // set default value for param
  }
}
Share:
14,001
sev
Author by

sev

Updated on June 30, 2022

Comments

  • sev
    sev almost 2 years

    I am writing my own jQuery functions. Is it possible to set the default values of the function parameters?

  • sev
    sev about 14 years
    Thanks a lot. It is what I find.
  • DemitryT
    DemitryT over 11 years
    Don't forget the semicolon at the end of the line. Even though JS will put those in for you where it can, it's good practice to do it yourself.
  • KingOfHypocrites
    KingOfHypocrites over 10 years
    This will fail with booleans. If you pass in false, and your default value is true, it will always be set to true.
  • KingOfHypocrites
    KingOfHypocrites over 10 years
    This will fail with booleans. If you pass in false, and your default value is true, it will always be set to true.