samedi 27 juin 2015

Else required if "if" ends with return?

This question might be close to opinion, or best practice, though I think the subject is defined enough to answer properly.

When in JavaScript there's a function that consists of an if statement and the if-statement ultimately ends in a return statement, is it required to add an else statement as well? An example to illustrate:

function is_fruit(boolean) {
    var banana = boolean,
        str = "I am fruit.";

    if (banana) return str;
    return str.replace("fruit","Groot");
}

alert(is_fruit(false));

In the above example we first check if the boolean is set to true. If it is, we simply return the var str (and considering we are using return, that's the end of the function all together!). However, when banana isn't true, we skip the if-statement and execute the rest of the function - in this case another return function.

In practice, this can be re-written as:

function is_fruit(boolean) {
    var banana = boolean,
        str = "I am fruit.";

    if (banana) return str;
    else return str.replace("fruit","Groot");
}

alert(is_fruit(true));

I prefer the second method because it's simply more intuitive and cleaner in my opinion. However, are there any other differences that need to be considered? E.g. is the first one faster (on a large scale)? Or is there no difference because JS executes synchronously? And so on. (To fit the format of SO: should I use the first or second method?)

Aucun commentaire:

Enregistrer un commentaire