Javascript/Jquery - Setting default value in function
Using javascript/jquery is there a way to set a variable to a default value if no value is passed in the function? For example
function someFunction(data1,data2)
{
}
If data1 or data 2 is empty it gives me an undefined value. In php I could do just this:
function somefunction(data1 = '',data2 = '')
{
}
So if no variable is passed or data1 or data 2 it defaults to ''. In JS/Jquery do I have to check if there is a value and set it accordingly?
function someFunction(data1,data2)
{
if(!data1) {
data1 = '';
}
if(!data2) {
data2 = ''
}
}
Just seems alot needs to be done开发者_StackOverflow社区 to check if variable is empty or not to give it a default value.
function foo(bar) {
bar = bar || 'default';
}
(Alternatively, if you only ever use bar
once, you can just replace that usage with bar || <default value>
and skip the intermediate assignment.)
function someFunction(data){
data = data || 'my value';
}
The only problem with this is that the 0
, false
and undefined
are treated the same:
someFunction(1); // data = 1;
someFunction(-1); // data = -1;
someFunction(); // data = 'my value';
someFunction(0); // data = 'my value';
someFunction(false); // data = 'my value';
You can use this:
function foo(optionalArg) {
optionalArg = optionalArg|| 'defaultValue';
}
as long as you never pass a value to the parameter. This logic fails if optionalArg is passed Try this instead:
function foo(optionalArg) {
optionalArg = (typeof optionalArg === "undefined") ? "defaultValue" : optionalArg;
}
You would use jquery's extend method but define defaults in the code like below
$.fn.myPlugin = function (settings) {
var options = jQuery.extend({
name: "MyPlugin",
target: document,
onOpen: function () {},
onClose: function () {},
onSelect: function () {}
}, settings);
}
now you could do
$("#divId").myPlugin({
target: $("#div2")
};
this will now override the document
target defined inside the defaults with element having div2 as id
.
精彩评论