3

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 to check if variable is empty or not to give it a default value.

4 Answers 4

27
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.)

Sign up to request clarification or add additional context in comments.

1 Comment

This works as long as bar is not allowed to have a value which evaluates to false. In this case, the longer ternary operator has to be used (to compare against the "invalid" value explicitly).
4
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';

Comments

4

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;
}

Comments

2

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.

2 Comments

I think this would only work for functions in jQuery plugins, right?
@bean5 Yes correct. If you want to build something that has to do with configuration and defaults i bet that piece of code is well worth written as plugin than global function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.