3

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

wattostudios
  • 8,666
  • 13
  • 43
  • 57
sev
  • 51
  • 1
  • 1
  • 4

5 Answers5

9

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
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
3

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

a = a || "something"

is probably the most concise and readable version.

Christian F
  • 352
  • 3
  • 5
  • 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. – DemitryT Aug 29 '12 at 19:55
  • This will fail with booleans. If you pass in false, and your default value is true, it will always be set to true. – KingOfHypocrites Sep 08 '13 at 18:44
2

You might want to check for undefined instead of null.

var f=function(param){
  if(param===undefined){
    // set default value for param
  }
}
Jeremy
  • 22,188
  • 4
  • 68
  • 81
0
(function($) {
    $.fn.yourFunction= function(opts) {
        var options = $.extend({}, $.fn.yourFunction.defaults, opts);

        ....

        $.fn.yourFunction.defaults = {
        param1: "someval",
        param2: "",
        param3: "#ffffff"
    };

})(jQuery);
rahkim
  • 911
  • 2
  • 9
  • 17
0

if not defined then a have "something"

a = a || "something"; // setting default value
Abdul Wahid
  • 167
  • 2
  • 8