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.