Learn the basics of if/else statements in JavaScript.
Computers read programs sequentially, one command at a time, from top to bottom. However, we typically want our programs to be non-sequential so that they can respond to the user or the outside world. In order to do this, we can use control structures. One important control structure is an if statement. You can use if statements to execute code only if a certain condition exists.
We actually use if statements in our everyday lives. Here are some examples:
Within these statements, it’s implied that if it’s not raining or if do not enter the correct passcode, you won’t need an umbrella and your phone will remain locked. Using if statements allows us to direct the computer to execute code only at certain times when a specific condition is true.
Here is the basic structure of an if the statement in JavaScript:
Boolean expressions are perfect for if statements because they are either true
or false
. If the boolean expression evaluates to true
, the code inside the brackets will run. If the boolean expression evaluates to false
, the computer will skip the code inside the brackets and continue on its way through the program.
Take a look at this example to see an if statement in action. Run this program and explore with these guiding questions:
isLocked
?isLocked
to false
and run the program?What if you want your program to do something if the boolean expression evaluates to false
? You can use an if/else statement!
Here is what an if/else statement looks like in JavaScript:
Take a look at the example. Run the program and explore with this guiding question:
isLocked
to false
? How is this different than the previous example?Let’s take a look at one more example. This program determines a shape based on the number of sides the user inputs. Notice how you can check for multiple conditions using else if
statements.
Run the program and explore with these guiding questions:
5
for the number of sides? Why is there no condition for numSides == 5
?else if
statement: numSides == 5
. What happens?Write a program that prompts the user for their age and determines if they are eligible to drive (16+ years old).
When run, your program should look like something this:
Hint: Take a look at the example for how to get input from the user!