Using 'return' instead of 'else' in JavaScript

后端 未结 13 1523
無奈伤痛
無奈伤痛 2020-12-01 14:09

I am working on a project which requires some pretty intricate JavaScript processing. This includes a lot of nested if-elses in quite a few places.

相关标签:
13条回答
  • 2020-12-01 14:40

    I always go with the first method. Easier to read, and less indentation. As far as execution speed, this will depend on the implementation, but I would expect them both to be identical.

    0 讨论(0)
  • 2020-12-01 14:45

    My understanding is that would not make a difference because you branch with the if condition. So, if some_condition is true, the else portion will not be touched, even without the return.

    0 讨论(0)
  • 2020-12-01 14:47

    There won't be any difference in performance I would recommend the second example for maintainability. In general it's good practice to have one and only one possible exit point for a routine. It aids debugging and comprehension.

    0 讨论(0)
  • 2020-12-01 14:47

    I will use the first approach when ruling out the invalid situations.

    Eg. use first approach when doing some validations, and return if any of the validation fails. There's no point in going further if any of the preconditions fail. The same thing is mentioned by Martin fowler in his Refactoring book. He calls it "Replacing the conditions with Guard clauses". And it can really make the code easy to understand.

    Here's a java example.

      public void debitAccount(Account account, BigDecimal amount) {
        if(account.user == getCurrentUser()) {
          if(account.balance > amount) {
               account.balance = account.balance - amount
           } else {
              //return or throw exception
           }
        } else {
            //return or throw exception
        }
      }
    

    VS

     public void debitAccount(Account account, BigDecimal amount) {
        if(account.user != getCurrentUser()) return //or error
        if(account.balance < amount) return //or error
        account.balance = account.balance - amount    
    }
    
    0 讨论(0)
  • 2020-12-01 14:48

    "Profile, don't speculate!"

    1. you're putting the cart before the horse (maintainability by humans trumps machine speed)
    2. you should drive your optimization efforts by measurements, which means

      • you should time the execution yourself; it'll obviously differ in different browsers and versions
      • you should only optimize for speed the hotspots of your application (see point 1)
    0 讨论(0)
  • 2020-12-01 14:48

    In my opinion, return and else is same for the above case but in general if-else and if()return; are very different. You can use return statement when you want to move from the present scope to parent scope while in case of if-else you can check for further if-else in the same scope.

    0 讨论(0)
提交回复
热议问题