Call break in nested if statements

Javascript

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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
}() );

Solution 2 - Javascript

no it doesnt. break is for loops, not ifs.

nested if statements are just terrible. If you can avoid them, avoid them. Can you rewrite your code to be something like

if (c1 && c2) {
    //sequence 1
} else if (c3 && c2) {
   // sequence 3
}

that way you don't need any control logic to 'break out' of the loop.

Solution 3 - Javascript

In the most languages, break does only cancel loops like for, while etc.

Solution 4 - Javascript

But there is switch-case :)

switch (true) {
	case true:
		console.log("Yes, its ture :) Break from the switch-case");
		break;
	case false:
		console.log("Nope, but if the condition was set to false this would be used and then break");
		break;
	
	default:
		console.log("If all else fails");
		break;
}

Solution 5 - Javascript

To make multiple checking statements more readable (and avoid nested ifs):

var tmp = 'Test[[email protected]]';

var posStartEmail = undefined;
var posEndEmail = undefined;
var email = undefined;

do {
    if (tmp.toLowerCase().substring(0,4) !== 'test') { break; }

    posStartEmail = tmp.toLowerCase().substring(4).indexOf('[');
    posEndEmail = tmp.toLowerCase().substring(4).indexOf(']');

    if (posStartEmail === -1 || posEndEmail === -1) { break; }

    email = tmp.substring(posStartEmail+1+4,posEndEmail);

    if (email.indexOf('@') === -1) { break; }

// all checks are done - do what you intend to do

    alert ('All checks are ok')

    break; // the most important break of them all

} while(true);

Solution 6 - Javascript

Javascript will throw an exception if you attempt to use a break; statement inside an if else. It is used mainly for loops. You can "break" out of an if else statement with a condition, which does not make sense to include a "break" statement.

JSFiddle

Solution 7 - Javascript

Actually there is no c3 in the sample code in the original question. So the if would be more properly

if (c1 && c2) {
    //sequence 1
} else if (!c1 && !c2) {
   // sequence 3
}

Solution 8 - Javascript

I had a similar problem today and found refactoring the conditional logic into a separate function to help.

I find it more readable than the labels and people are more comfortable with return than break. Inline functions are similar but the indentation can get a bit confusing.

In your case it would look like this.

function doThing() {
  checkConditions();

  // Rest of the code here
}

function checkConditions() {
  if (c1) {
    if (c2) {
      return do1();
    else {
      return;
    }
  } else {
    return do3();
  }
}

Solution 9 - Javascript

Just remove the break. since it is already inside first if it will not execute else. It will exit anyway.

Solution 10 - Javascript

You need that it breaks the outer if statement. Why do you use second else?

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

sequence 4

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionUpCatView Question on Stackoverflow
Solution 1 - JavascriptDaniel LewisView Answer on Stackoverflow
Solution 2 - JavascripthvgotcodesView Answer on Stackoverflow
Solution 3 - JavascriptVan CodingView Answer on Stackoverflow
Solution 4 - JavascriptRobbaView Answer on Stackoverflow
Solution 5 - JavascriptDoctor RudolfView Answer on Stackoverflow
Solution 6 - JavascriptKJYe.NameView Answer on Stackoverflow
Solution 7 - JavascriptRobertView Answer on Stackoverflow
Solution 8 - JavascriptCrazometerView Answer on Stackoverflow
Solution 9 - JavascriptD NootanaView Answer on Stackoverflow
Solution 10 - JavascriptmiqbalView Answer on Stackoverflow