10

I have always written my JavaScript blocks

var functionName = function() {
  if (someCondition) {
      // stuff
  } else {
      // stuff
  }
};

but today I saw

var functionName = function() {
  if (someCondition) {
     // stuff
     return;
  }
  // stuff
};

I like that the first example is more explicit in the logic. What are some reasons why you would or wouldn't want to do it the second way demonstrated?

Mike Grace
  • 15,387
  • 8
  • 55
  • 78

3 Answers3

12

Less indentation in case you got more then one someCondition.

Imagine:

var functionName = function() {
    if (someCondition) {
        // stuff
    } else {
        // stuff
        if (someConditionB) {
            // stuff

        } else {
            // stuff

            if (someConditionC) {
                // stuff

            } else {
                // stuff

                if (someConditionD) {
                    // stuff
                } else {
                    // stuff
                }
            }
        }
    }
};

Which would be a lot more readable without all the elses:

var functionName = function() {
    if (someCondition) {
        // stuff
        return;
    }

    if (someConditionB) {
        // stuff
        return;
    }

    if (someConditionC) {
        // stuff
        return;
    }
    if (someConditionD) {
        // stuff
        return;
    }

    // stuff
};
Sibi
  • 43,989
  • 14
  • 80
  • 146
Ivo Wetzel
  • 44,463
  • 14
  • 89
  • 109
4

Many coding standards mandate that you shouldn't "early exit" from functions. It's a trade-off between readability, and "correctness" [*]

The early exit avoids the need for the subsequent code to be indented in an extra level. For example, IMHO it makes sense to have some error detection checks grouped together at the top of functions with an early exit on failure, with the meat of the function written as normal.

On the other hand, when reading code for debugging purposes it's easy to miss the early exit, and end up trying to find a bug in the wrong part of your code.

[*] those same code standards often eschew usage of break and continue. FWIW I think it's a symptom of over application of Djikstra's "GOTO considered harmful" mantra.

Alnitak
  • 313,276
  • 69
  • 379
  • 466
1

You may want to use method 2 in 2 cases:

Case 1: You have more stuff after your logic that you do not want run. The code executed does all you need and you don't need the extra stuff.

Case 2: Depending on what the function is attached to, you want to return a false to prevent an action. Once such instance would be an onSubmit for a form, and validate the input. If it is bad, immediately return false and prevent the form from submitting.

rayman86
  • 1,335
  • 10
  • 9