Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit from if block in Javascript

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
        }
}
like image 649
python-coder Avatar asked Nov 22 '13 07:11

python-coder


People also ask

Can we use break in if JavaScript?

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.

How do you exit a loop if condition is met in JavaScript?

TL;DR: use break to exit a loop in JavaScript.

How do I stop a JavaScript script?

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.


2 Answers

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

like image 130
MoweMax Avatar answered Oct 24 '22 16:10

MoweMax


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...

like image 36
Trentium Avatar answered Oct 24 '22 16:10

Trentium