Exit from if block in Javascript

if-statement, javascript

Solution

Super late to the party, but for folks from search, you can use something called `labeling`. It's not good practice, but in rare cases that can be applied. Basically you can assign a name to the `if` statement that you want to break from. And anywhere in statement call `break` from specified name.

Code example:

my_if: if (condition) { 
    // do stuff
    break my_if;
    // not do stuff
}

in your particular case:

id1: if ($('#id1').length > 0) {
    if(yester_energy == "NaN" || yester_energy == 0){
        break id1;
    }else{
      //something
    }
    $("#abc").html(somthing)
}

More about `labeling` can be found here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label#Syntax

Problem

I want to exit from the below if block in Javascript. if I return, then it does not check for the next if condition. How do I do that? ``` if ($('#id1').length > 0) { if(yester_energy == "NaN" || yester_energy == 0){ //break from #id1 } else{ //something } $("#abc").html(somthing) } if ($('#id2').length > 0) { if(yester_energy == "NaN" || yester_energy == 0){ //break from #id2 } else{ //something } } ```

Original source