Reputation: 2859
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.
Upvotes: 4
Views: 2767
Reputation: 386560
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();
Upvotes: 6