Conditional Statements

Conditional statements determine when and where to execute code based on conditions. They let us perform a set of actions for a specific set of rules.

Conditional statements have a variety of use cases, in our earlier example we used conditional statements to toggle animation data-attributes. If the animation attribute was slide-in we changed it to slide-out. If there was no slide-in attribute we added it.

The if...else Statement

This YouTube video was created by Steve Griffith.

This Scrimba screencast was created by Dylan C. Israel.

We can make specific checks for specific values in our code. In this example we have two conditions, if the number is 9, or if the number is 10. We set the number to 10 and the condition for if the number is 10 is true. Because the number is not 9 the code above that condition is not run.

 

If a condition is met do one thing, if it's not met do another thing. In this example if the time is 10:00PM we will go to bed, but if the time is not 10:00PM that means we still have lots of time for video games.

The else if Clause

We can also check for more than one value before our else catches everything else.

Let's take a look at a little schedule reminder.  At a specific time of day the screen will notify us what to do.

The switch Statement

This YouTube video was created by Steve Griffith.

This Scrimba screencast was created by Dylan C. Israel.

Comparison Operators

Equality Operators

This YouTube video was created by Steve Griffith.

Less than

In some cases we will want to see if the match is anything less than the value we're looking to compare. In this example, if the value we set to the variable a is less than 10 the condition is true. We set the value to 8 and because 8 is less than 10 the condition is met.

Greater than

Vice Versa we can check to see if something is greater then a specific value. Here we set the value of a to 8 and check to see if that is greater than 5. 8 is greater than 5 and the condition is met.

Greater than or equal to / Less than or equal to

Let's see what happens when we set the value to 5 and check to see if the value is less than 5 or greater than 5 with two separate conditions. Notice nothing is printed to the screen.

Neither condition is met, 5 is neither greater than or less than 5. It's equal to 5.  We can perform additional checks to see if the value is less than or equal to 5. Or greater than or equal to 5.

Logical Operators

This YouTube video was created by Steve Griffith.