Question

I am trying to make my javascript conform to the best practice for returning values from a function. Currently, I declare a variable, process that variable in the function and then return it. I thought it was good practice to explicitly state things, but I am wondering if that's just a myth in my head and there are better ways. So of the two methods, or even neither of these, which is best? Thanks

Example A:

function foo( a ){

    var str = "";

    if (a == "bar"){
        str = "barbar";
    } else {
        str = "foofoo";
    }

    return str;
}

Example B:

function foo( a ){

    if (a == "bar"){
        return "barbar";
    } else {
        return "foofoo";
    }
}
Was it helpful?

Solution

In Javascript there is a very small performance improvement for B as in example A you have an additional variable str that must be looked up in the local scope 3 times (initialise, set one or other value, and return).

Example A is actually something like this under the covers (note that you can't actually explicitly access the local object, any var you declare is on it automatically):

function foo( a ){

    local["str"] = "";

    if (a == "bar"){
        local["str"] = "barbar";
    } else {
        local["str"] = "foofoo";
    }

    return local["str"];
}

However, you will need to hit this a lot of times to see the difference - it's going to be near negligible, and possibly eliminated completely in the latest optimised Javascript engines (as seen in better browsers). I'm pretty sure Chrome's V8 engine does.

Outside of that it is a question of coding style - many teams prefer A because you can set a watch on str and always know what it holds. Personally I prefer B because it's more spartan and because I find short-circuited logic easier to follow, but many developers don't like it because if they miss an early return they can find bugs hard to follow.

It's really a 'house style' question.

OTHER TIPS

In Example B you could do the following and that would be what I would do, you don't need the extra else since you are returning if you evaluate true:

function foo( a ){
    if (a == "bar"){
        return "barbar";
    }
    return "foofoo";   
}

In your example I'm not sure if either one is technically better. A good use case for this would be inside of a loop, if you get the result that you're looking for, then return the value immediately. If you do it this way your loop won't have to continue executing when you already got the result you wanted.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top