tags:

views:

782

answers:

3

What would be the most idiomatic way to do the following in javascript:

If myParam is not passed into MyFunc by the caller, then I want to set it to a default value. But first I want to try and get it from another object, which may not yet exist:

function MyFunc(myParam) {

    if (!myParam) {
        if (!myObj) {
            myParam = 10;
        }
        else {
            myParam = myObj.myParam;
        }
    }

    alert(myParam);
}

I started to write:

    myParam = myParam || myObj.mParam || 10

but realized that if myObj does not exist then this would fail. I might guess the following:

    myParam = myParam || (myObj && myObj.mParam) || 10

It might even work. But is it the best way?

How would for example John Resig do it?

+3  A: 

If myObj is a global it needs to reference the window object, otherwise it will throw an error if myObj is undefined.

myParam = myParam || (window.myObj ? window.myObj.mParam : 10);

or

myParam = myParam || (window.myObj && window.myObj.mParam) || 10;

This works as well:

myParam = myParam || ((typeof myObj !== "undefined") ? myObj.mParam : 10);
Luca Matteis
throws an error if myObj doesn't exist.
Triptych
Yeah overlooked that one.
Luca Matteis
Just remember that 0, empty string, null, false, NaN and undefined all are false and will in the two examples above give you the default value. In the third example you only get the default value if myObj is undefined, regardless if the myObj.mParam is assigned or not.
some
A: 
myParam |= (myObj || {}).mParam || 10;
toby
This is more golfy than idiomatic. I do not commonly see this construct.
Triptych
What the hell? Who let bitwise or in? (ie, this doesn't work)
Crescent Fresh
actually, it also doesn't work if myObj is undefined.
Triptych
even if it worked as intended, it would allocate a useless object, only to drop it as garbage immediately.
Javier
My bad on this one. |= doesn't work. Feel free to vote this down. It's okay =)
toby
A: 

I think the other answers have proven that there are a whole bunch of ways a one-liner can fail here. My version below is perhaps more readable, and doesn't explicitly test for object/property existence, but isn't much shorter:

function MyFunc(myParam){
    if (!myParam){
        try{
            myParam = myObj.myParam;
        }
        catch(e){
            myParam = 10;
        }
    }
}
Triptych