Lexone Lexone - 4 months ago 12
Javascript Question

Javascript elseif/if else help needed

I'm quite new to coding and I've never understood what's the proper way to do the following:

if (something == true) {
DoSomething();
} else {
if (something2 == true) {
DoSomething2();
}
DoSomethingAnyways();
}


I've heard using
else if
is the right way to do this, but how can I execute the
DoSomethingAnyways();
if I use
else if
?

Basically what I'm asking is how can I write this using else if and have the exact same effect?

if (something == true) {
DoSomething();
} else if (something2 == true) {
DoSomething2();
DoSomethingAnyways(); //<-- Where do I put this line of code?
}

Answer

There's nothing wrong with the way you've done it. else if is for cases like this:

if (foo) {
  doSomething()
}
if (!foo && bar) {
  doSomethingElse()
}
if (!foo && !bar) {
  nothingWorked()
}

which works the same as this:

if (foo) {
  doSomething()
} else if (bar) {
  doSomethingElse()
} else {
  nothingWorked()
}

However your example doesn't fit this pattern.

See also part of the jQuery source. Not quite the same, but similar.