3

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

5 Answers 5

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

Comments

3

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

a = a || "something"

is probably the most concise and readable version.

2 Comments

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.
This will fail with booleans. If you pass in false, and your default value is true, it will always be set to true.
2

You might want to check for undefined instead of null.

var f=function(param){
  if(param===undefined){
    // set default value for param
  }
}

Comments

0

if not defined then a have "something"

a = a || "something"; // setting default value

1 Comment

This will fail with booleans. If you pass in false, and your default value is true, it will always be set to true.
0
(function($) {
    $.fn.yourFunction= function(opts) {
        var options = $.extend({}, $.fn.yourFunction.defaults, opts);

        ....

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

})(jQuery);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.