“elseif” syntax in JavaScript

后端 未结 8 932
刺人心
刺人心 2020-11-29 17:59

How can I achieve an elseif in a JavaScript condition?

8条回答
  •  北海茫月
    2020-11-29 18:38

    In JavaScript's if-then-else there is technically no elseif branch.

    But it works if you write it this way:

    if (condition) {
    
    } else if (other_condition) {
    
    } else {
    
    }
    

    To make it obvious what is really happening you can expand the above code using an additional pair of { and }:

    if (condition) {
    
    } else {
    
       if (other_condition) {
    
       } else {
    
       }
    
    }
    

    In the first example we're using some implicit JS behavior about {} uses. We can omit these curly braces if there is only one statement inside. Which is the case in this construct, because the inner if-then-else only counts as one statment. The truth is that those are 2 nested if-statements. And not an if-statement with 2 branches, as it may appear on first sight.

    This way it resembles the elseif that is present in other languages.

    It is a question of style and preference which way you use it.

提交回复
热议问题