You Can Learn How to Code
Introduction to conditional logic in JavaScript

If / Else Statements in JavaScript

Understanding if / else statements and other types of conditional logic is an essential skill for programmers. As you start to write more complex programs, you’ll find that you’ll start relying heavily on conditional logic. If else statements in JavaScript, for example, will instruct the browser to execute code (or not), if a specified condition is true. As the programmer, you get to decide which conditions must be met in order for the code to run.

Like much of programming, if else statements have their roots in mathematics. If-then statements are an important part of Geometry proofs. If you do not remember your high school math lessons, though, do not worry. I am going to break this concept down step by step.

The Root of If / Else Statements

if then statements graphicIn Geometry, deductive logic is used in proofs. Here is an example: It is a given that the formula for the area of a circle is π multiplied by the radius squared. Therefore, if the radius of a circle is 9, then the area of the circle is 81π.

We can also break down deductive logic into a non-mathematical construct: If I get less than six hours of sleep, then I will feel tired the next day. In the most basic form of deductive logic, that’s all there is to it: if x is true, then one can conclude y.

How Does this Relate to Programming?

In many cases, you do not want your code to execute unless certain conditions are met. In my line of work, for example, I build a lot of web forms for students. What if the student forgets to add his name to the form? We would not want him to be able to submit the form because the administrator or program manager wouldn’t know whom to contact, and it would cause us a lot of time to track down the student.

if else statements graphicAs a web programmer, decide which fields must be filled out before a form can be submitted. I can write instructions to the browser to not submit the form if a user leaves his name field blank. Instead, I can instruct the browser to issue an alert and draw the user’s attention to the blank field.

This is where conditional logic differs slightly from deductive logic. In the deductive logic used in Geometry proofs, the syntax used is if / then. In conditional logic, which is what is used in programming, the syntax is if / else. The programmer instructs the computer (or the browser) to execute a task or run a program only if a certain condition is met.

Getting back to our form example, the conditional logic is, if all required fields have data, submit the form. Else, alert user to fill in required fields. The “required” HTML attribute now performs this validation in the browser, negating the need for JavaScript, but it is good to understand where this concept originated.

How To Add If Else Statements to Your Code

Teenaged girl working at computerYou can also use if / else statements for situations that require granting permission. Let’s say you’re building a teen-friendly website but the company you’re building it for doesn’t necessarily think it should be used by grammar school aged children because it explores teen issues. As the programmer, you could write code that checks the age of users by requiring them to enter their ages. If a user is under a certain age, he cannot use the program, and your code will alert him to this fact.

var userAge = prompt(“How old are you?”);if (userAge < 12) {

alert(“We are sorry. You are too young to use this website.”);

} else {

alert(“Welcome to Exploring Teen Issues.”);

}

In this example, we use a variable (note the var keyword) to save the value of the user’s age so that it can be used in the program. The prompt method alerts the user to enter his age and saves it to the userAge variable. Once that happens, the rest of the program runs. Users who are under twelve years of age, receive a message stating that they’re too young to use the website whereas users older than twelve are free to use the website.

The information in parentheses following the if is known as a condition. If the condition is met, then do not grant access to the website.

Conversely, the program could be re-written as follows:

if (userAge > 12) {alert(“Welcome to Exploring Teen Issues.”);

} else {

alert(“We are sorry. You are too young to use this website.”);

}

The difference is that if the first condition is met, as in the user is greater than twelve years of age, he will be alerted that access to the website will be granted.

How to Add a Third Condition

Let’s say that the web app is a big success and more and more preteens are getting interested in the web service. They’d like to use it, too, but the company you’re writing the program for is worried about the legal implications of granting access to kids who are younger than 12. So, they decide to amend the terms of service and grant access to kids who are nine to 12 years of age, but only if a parent or guardian is present.

As a programmer, you can add a third condition to this code with an else if statement.

var userAge = prompt(“How old are you?”);if (userAge < 9) {

alert(“We are sorry. You are too young to use this website.”);

} else if (userAge < 12) {

alert(“You may use our website as long as your parent or guardian is present.”)

} else {

alert(“Welcome to Exploring Teen Issues.”);

}

After a user enters his age, the program will first check to see if the user is younger than 9 years old. If so, the user will receive an alert that he’s too young to use the website. (userAge < 9) is the first condition of the program. If this condition is met, access will be denied.

Next, the program will check to see if a user is between nine and 12 years of age. This is accomplished with an else if statement. At this point, you might be wondering why you do not have to specify the lower end of this condition, as in greater than nine and less than 12. I wondered about this constantly when first learning about if / else statements and eventually realized that because the program had already checked to make sure the user was greater than nine, that anyone younger than nine would be ruled out. Therefore, the youngest age the computer checks for at this point in the program is nine years old, so it doesn’t have to be specified.

Users between nine and 12 years of age will receive an alert that they can use the website if a parent is present. And finally, anyone older than 12 will receive the welcome message.

Conditional Logic Gives You Options

If, else if, and else statements give you the ability to make decisions in your code. No matter which programming language you choose to learn, you will rely on conditional logic in some form. We can use else if statements in JavaScript to guide users down any number of paths. In addition to checking a user’s age as in the example in this article, web scripting gives us the option to also check things like making sure a user’s password matches what is stored in the database before granting access, alerting a user that the credit card on file has expired, checking to make sure that a linked debit card has sufficient funds, and much more.

If you’re looking for more practice with conditional logic, check out this lesson at W3Schools or Colt Steele’s course The Web Developer Bootcamp.

2 comments

  1. Hi Laura! Great post on the If/Else statement! Such an important concept to grasp…without an understanding of conditionals, you are going to be very limited in what you can code.

    My daughter is just getting into programming…I’m going to share your website with her as it looks like a great place to get started. (She is mostly interested in website development).

    Thanks again for the great post. We’ll be checking back for new content!

    1. Thanks for the kind words! Glad you’ll be back for more — I have some exciting topics planned. Your daughter is welcome to contact me with any questions if she’s having trouble getting started. I wish her the best in her journey of learning web development.

Leave a Reply

Your email address will not be published. Required fields are marked *