Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to break out of an if block in JavaScript?

In an if block structure, such as below, suppose that condition_1 and condition_2 are mutually exclusive but there are times when condition_2 and later conditions can both be true; and, when condition_2 is true, all that is desired is to break out of the if block and continue with the rest of the code, similar to a switch statement.

All the conditions, except condition_2, are matches statements for a listener on a parent container with several buttons. When condition_2 is true, the buttons below it should be disabled.

if ( condition_1 ) { }
else if ( condition_2 ) {  }
else if ( condition_3 ) {  }
else if ( condition_4 ) {  }
// ...
else if ( condition_n ) {  };   
// More code in the function before returning.

It could be coded as:

if ( condition_1 ) { }
else if ( !condition_2 && condition_3 ) {  }
else if ( !condition_2 && condition_4 ) {  }
// ...
else if ( !condition_2 && condition_n ) {  };   
// More code in the function before returning.

or

if ( condition_1 ) { }
else if ( !condition_2 )
  {
    if ( condition_3 ) {  }
    else if ( condition_4 ) {  }
    // ...
    else if ( condition_n ) {  };   
  };
// More code in the function before returning.

Would it be a "bad" programming practice to just code as in the first block and just place no code between the braces for condition_2, such that when condition_2 is true, there's no code to perform but the other conditions are not tested and it picks up with the code at the end of the if block?

Is there a better more professional way to do accomplish the same?

I read about putting a label on the if statement and then using break label, but I don't see what that adds; and it was mentioned that the method might not be efficiently employed by the compiler/interpreter.

Thank you.

like image 459
Gary Avatar asked Sep 14 '25 23:09

Gary


1 Answers

You could take a labeled statement and break the block statement{}, if a condition is true.

var a = 2;
block: {
    if (a === 1) {
        console.log(1);
        break block;
    }
    if (a === 2) {
        console.log(2);
        break block;
    }
    if (a === 3) {
        console.log(3);
        break block;
    }
    console.log('end of block');
}

Or take another nested function in the same scope and return early.

function check () {
    if (a === 1) {
        console.log(1);
        return;
    }
    if (a === 2) {
        console.log(2);
        return;
    }
    if (a === 3) {
        console.log(3);
        return;
    }
    console.log('end of function');
}

var a = 2;
check();
like image 152
Nina Scholz Avatar answered Sep 16 '25 12:09

Nina Scholz