开发者

JavaScript condition block vs blank return for control flow

I have always written my JavaScript blocks

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

but today I开发者_StackOverflow社区 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?


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
};


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜