Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call break in nested if statements

Tags:

javascript

I have the following situation:

IF condition THEN       IF condition THEN          sequence 1     ELSE         break //?       ENDIF     ELSE         sequence 3     ENDIF 

What is the result of the break statement? Does it break the outer if statement? Because this is what I actually need.

like image 206
UpCat Avatar asked Jan 31 '11 13:01

UpCat


People also ask

Does Break work in nested IF?

In a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues. However, if the break is placed in the outer loop, all of the looping stops.

How do you break out of a nested IF statement?

We can use an alternative method to exit out of an if or a nested if statement. We enclose our nested if statement inside a function and use the return statement wherever we want to exit.

Does Break Break out of if statements?

breaks don't break if statements. But break s don't break out of if s. Instead, the program skipped an entire section of code and introduced a bug that interrupted 70 million phone calls over nine hours. You can't break out of if statement until the if is inside a loop.

Can I use break in if statement JS?

If you label the if statement you can use break. You can even label and break plain blocks. It's not a commonly used pattern though, so might confuse people and possibly won't be optimised by compliers. It might be better to use a function and return, or better arrange the conditions.


1 Answers

If you label the if statement you can use break.

breakme: if (condition) {     // Do stuff      if (condition2){         // do stuff     } else {        break breakme;     }      // Do more stuff } 

You can even label and break plain blocks.

breakme: {     // Do stuff      if (condition){         // do stuff     } else {        break breakme;     }      // Do more stuff } 

It's not a commonly used pattern though, so might confuse people and possibly won't be optimised by compliers. It might be better to use a function and return, or better arrange the conditions.

( function() {    // Do stuff     if ( condition1 ) {        // Do stuff     } else {        return;    }     // Do other stuff }() ); 
like image 131
Daniel Lewis Avatar answered Oct 10 '22 20:10

Daniel Lewis