How can I create a fallback for a series of JavaScript if statements?

Viewed 206

So I want to do something that would allow me to have a form or text field ( tag in html) and basically I can type something into that field and have something else happen

For example:

if (x === "something") {
    then do this set of instructions
}

if (x === "something else") {
    then do this different set of instructions
}

else {
  alert("Some error message")
}

In the example above, is it possible to do something where I can type "something" and have it do that set on instructions but not show the alert in the else {} statement?

The different sets of instructions are different and the "something" and "something else" are also different, but the x is in reference to the tag which is inside a tag.

But basically if any of the "if" statements are met, do not execute the "else" statement. But if any of the "if" statements are not met, then execute the else statement. Not sure if it's possible, but I have no clue, just started working with js, so sorry if this is a very basic thing.

4 Answers

Use

if(x === "something") {
  then do this set of instructions
} else if (x === "something else") {
  then do this different set of instructions
} else {
  alert("Some error message")
}

Plus, the answer is kind of obvious!

Take a look at the switch statement.

switch(x) {
  case 'something': {
    do this set of instructions;
    break;
  }
  case 'somethingelse': {
    do this other set;
    break;
  }
  default: {
    some error message 
  }
}

This... Is exactly how if statements work if I understood correctly. If a condition is True, execute this set of instructions. If it's not, execute this other set of instructions (alert an error)

Though you might be referring to the else if statement. In this case, else will only run if x isn't equal to something else. Change the code to:

if (x === "something") {
    then do this set of instructions
} else if (x === "something else") {
    then do this different set of instructions
} else {
  alert("Some error message")
}

And you should be good.

If I'm understanding your wording, you would like to be able to execute any arbitrary number of if statements, and then not execute your else if any of the if statements have been entered. There is not a native built-in logic structure that does this, but it can be easily achieved using a variable in the containing scope that is flipped if any of the if statements is entered:

let enteredAnIf = false;

if (aThing) {
    // do some stuff
    enteredAnIf = true;
}

if (aDifferentThing) {
    // do some different stuff
    enteredAnIf = true;
}

if (!enteredAnIf) {
    // this is your "else", entered only if none of the above `if` 
    // statements flips the `enteredAnIf` to `true`
}
Related