DEV Community

Cover image for If_Else If Statements: The Quick Guide For Beginners
Deborah Kurz
Deborah Kurz

Posted on

If_Else If Statements: The Quick Guide For Beginners

(See The Header Image For How An If_Else If Statement Is Basically Written In A Function)

JavaScript likes to "solve" If_Else If Statements like flipping through a catalog...

...in search of something to buy - "If you don't want thing1, move on to thing2, and if you don't want thing2, move on to thing3, etc. Finally, if nothing else works, just get the basic model". Let's explore this a little more:

Our function starts out by checking the condition with the block of code to the right of the "if". This is our starting place, so it get's the special "if" name. If the condition is true (it matches exactly with the thing we've defined to the right of the ===), the function will return something from this block of code, then exit the function.

BUT, if the condition is FALSE, (it DOESN'T match exactly with the thing we've defined to the right of the ===), the function will move on and run the "else if" part of the code. If the condition is true (it matches exactly with the thing we've defined to the right of the ===), the function will return something from that block of code, then exit the function.

We can have multiple "else if" parts of the code - one for each option we want - and if the previous "else if" statement returns false, the next "else if" statements will be checked. This will continue until either 1)one of the "else if" statements returns true, or 2)there are no more "else if" statements left, in which case we move on to the last part of our code:

If nothing has returned true by the time we reach "else" (notice, this is the last part of the code and is NOT written "else if"), then the "else" part of the code will run and return something from that block of code.

It is important to remember that SOMETHING will be run: we have many options for what to run if something matches our "if" or "else if" parts of the code... but if nothing matches these parts, the "else" part of the code WILL run.

You can remember when to use If_Else If Statements like this:

If not Option1 or Option2 or Option3 (etc.), do the Final Option.

Top comments (0)