I am writing my own jQuery functions. Is it possible to set the default values of the function parameters?
5 Answers
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
}
Comments
i can't vote right now but agree with color2life.
a = a || "something"
is probably the most concise and readable version.
2 Comments
DemitryT
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
This will fail with booleans. If you pass in false, and your default value is true, it will always be set to true.
if not defined then a have "something"
a = a || "something"; // setting default value
1 Comment
KingOfHypocrites
This will fail with booleans. If you pass in false, and your default value is true, it will always be set to true.