Why would Javascript `if…else if` not end with an `else`?

后端 未结 8 1854
误落风尘
误落风尘 2020-12-16 02:23

Here is a snippet of JavaScript code from a tutorial I was working with. I don’t understand why it doesn’t end with a final else clause; I thought that was a ru

相关标签:
8条回答
  • 2020-12-16 02:50

    else is a default case for the if statement. If there is no else then if none of the conditions in the if or else if cases are met than the if statment will do nothing.

    Usually it is good practice to have a default case but there are a lot of times where it is not necessary and thus excluded from the code.

    In this case, if the curScene was anything other than 1, 2, 3 then the else statment would be used, but since there is no processing to be done on other cases the coder has not included an else.

    0 讨论(0)
  • 2020-12-16 02:50

    yes, always have a else is VERY GOOD habit(when using with if-elseif). sometimes people might even write this:

    if(curScene == 1) {
        message =" welcome";
    else if (curScene == 2) {
        message = " this is scene two";
    }
    else if (curScene == 3) {
        message = " this is scene three";
    } else {
        // empty.
    }
    

    to tell people there is indeed nothing to do in the else.

    0 讨论(0)
  • 2020-12-16 02:51

    It doesn't have to, for the same reason an if on its own doesn't require an else.

    Usually it's a good idea to have one, as a sort of "catch-all" situation, but the above code could be written as:

    switch(curScene) {
        case 1: message = " welcome"; break;
        case 2: message = " this is scene two"; break;
        case 3: message = " this is scene three"; break;
    }
    

    In the above code, I could also add:

        default: message = " invalid curScene value"; break;
    

    But it's completely optional to do so. It depends on how reliable the curScene variable is whether or not I personally would add it in.

    0 讨论(0)
  • 2020-12-16 02:53

    I thought it was always supposed to end with an "else"?

    The else block is optional. You can have if without else.

    0 讨论(0)
  • 2020-12-16 03:04

    change the if condition for answer validation if(answer==100) to if(answer===100) it is working fine now...

    0 讨论(0)
  • 2020-12-16 03:05

    For the same reason as why you can have just a single if:

    if( /*condition*/ ) {
        //some code
    }
    
    //other stuff
    
    0 讨论(0)
提交回复
热议问题