Control Flow If, Else If, and Else

02.08.2018 |

Episode #4 of the course Fundamentals of JavaScript by Matt Fay

 

Today, we’ll extend on what we’ve learned from the last lesson, only we’re going to add in some more logic and allow our programs to make decisions.

 

If Statements

Let’s say we have a website set up that has a certain age limit. We want to filter out people who are older than 18 years of age but younger than 25.

var minimumAge = 18;
var userAge;

if (userAge >= minimumAge) {
    // Proceed to site
}

 

Else Statements

What if the user’s age isn’t greater than or equal to 18? Well, that’s to be decided upon with an else statement:

var minimumAge = 18;
var userAge;
// If user is 18 or older, proceed.
if (userAge >= minimumAge) {
    // Proceed to site
}
// Else, user is not 18 or older, apologize.
else {
    // Sorry. For 18+ only!
}

Let’s recap. Our code knows what to do if someone is over the age of 18: It lets them proceed to the site. However, if they’re not over 18, they’ll receive a message: “Sorry. For 18+ only!”

 

Else If Statements

We’ve left out an important piece of code. As of now, anyone 18 or older is able to view our website! Luckily, we can easily fix this with an else if statement.

var minimumAge = 18;
var userAge;
// If user is 18 or older, proceed.
if (userAge >= minimumAge) {
    // Proceed to site
}

// Else if user is 25 or older, apologize.
else if (userAge >= 25) {
    // Sorry. Age limit reached!
}

// Else, user is not 18 or older, apologize.
else {
    // Sorry. For 18+ only!
}

That’s nice, no? We can make it much more efficient and easier to read by making use of the logical operators we learned about in Lesson 3.

var minimumAge = 18;
var userAge;
// If user is 18 or older, and user is 25 or below, proceed.
if (userAge >= minimumAge && userAge <= 25) {
    // Proceed to site
}
// Else, user is not between the ages of 18 and 25, apologize.
else {
    // Sorry. For 18+ only!
}

That’s all there is to it! We can imagine how we use such logic in our everyday life: If it is raining, grab an umbrella. Else, if it’s not raining, proceed outside. If/else decisions are vital to programming; they’re used in just about every programming language. Perhaps you can start imagining now where they might be. Click a button? There might be some logic in there making use of an if statement: If user clicks button, do something.

If you’d like to experiment in the console, you can try out the code below.

// Ask user for age:
var userAge = prompt(“Enter your age:”);

// If user’s age is greater than or equal to 18, send them a message.
if (userAge >= 18) {
    alert(“You’re an adult!”);
}

// Else, send them a different message.
else {
    alert(“You’re young!”);
}

In tomorrow’s lesson, we’ll go over loops, a fun way to do something many times with less code.

 

Share with friends