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
}
}
Author by
sev
Updated on June 30, 2022Comments
-
sev almost 2 years
I am writing my own jQuery functions. Is it possible to set the default values of the function parameters?
-
sev about 14 yearsThanks a lot. It is what I find.
-
DemitryT over 11 yearsDon'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 over 10 yearsThis will fail with booleans. If you pass in false, and your default value is true, it will always be set to true.
-
KingOfHypocrites over 10 yearsThis will fail with booleans. If you pass in false, and your default value is true, it will always be set to true.