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
        }
}
                A break statement, with or without a following label, cannot be used within the body of a function that is itself nested within the current loop, switch, or label statement that the break statement is intended to break out of.
TL;DR: use break to exit a loop in JavaScript.
Using return: In order to terminate a section of the script, a return statement can be included within that specific scope. In the presence of return: No output will be shown since the program is terminated on encounter.
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
Even later to the party... Typically in such situations, I use a combination of if and do...while as follows...
if ( condition ) do {
  // processing
  if ( exit_condition ) break;
  // more processing...
} while ( false );
Thus, when the break is encountered, it applies to the do...while loop, and processing continues after the while, effectively breaking out of the outer if statement...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With