Home > Software design >  How to exit or break out from an else if
How to exit or break out from an else if

Time:08-24

I've searched for a couple stackoverflow questions although couldn't find my answer.

I'm trying to break from an else if statement and was wondering if there was a more efficient way.

Heres a snippet:

var argument = "something";

if(argument == 'not_this'){
  // this doesn't trigger
} else if(argument){
  // this triggers although if the functions in here doesn't match what I want, 
  // how do I make It skip to the else statement without adding another else
  // if statement? 
} else {
  // do something if both statements above fail
}

Is there something that I can do which exits from the else if(argument)... without adding another else statement? I've tried using switch and case although those don't seem to help.

Thanks.

CodePudding user response:

You could set a flag that is by default true, and whenever the argument is valid you set it to false.

Then, to know when to execute the 'else' block, you can just check whether the flag is true or not:

var argument = "something";
let invalid = true

if (argument == 'not_this') {
  // this doesn't trigger
  invalid = false
} else if (argument) {
  if (typeof argument != 'string') {
    //valid
    invalid = false
  }
}

if (invalid) {
  console.log('invalid')
}

CodePudding user response:

Restructure the code to avoid confusing states, move out the if 'has value' check.

if (argument) {
  if (argument === 'not_this') {
    // this doesn't trigger
  }
} else {
  // do something if both statements above fail
}

For equality, it is safer to use strict equal === instead of loose equal ==

CodePudding user response:

You could try using return; to break out of the statement, as that would stop all other code from being read.

  • Related