IF Statements in JavaScript

This tutorial is part of a web programming course for people who have no programming experience.

We use IF statements to control the flow of code execution in JavaScript. For example, if a certain condition is true, then we may want some code to run. But if it is false, then we may want some other code to run.

An IF statement is known as a control structure. There are other control structures in JavaScript, we'll learn more about them soon.

Here is the basic structure an syntax for writing an IF statement in it's simplest form:

if(boolean expression goes here){

  // the code inside these curly braces
  // will run if the boolean expression
  // evaluates to true


Before we continue, please take a moment to notice the syntax (remember that mastering the syntax of a language is one of the biggest hurdles to a beginning programmer). It starts the keyword if, which must use lowercase letters. Then comes a boolean expression that is enclosed within parenthesis (we'll discuss boolean expressions next). Directly after the closing parenthesis, we have an opening curly brace. The matching closing curly brace marks the end of this IF statement. Note that curly braces, like paranthesis, always come in pairs It's a common mistake for beginning programmers to forget an opening or closing curly brace, which can lead to bugs and frustration. You put code in between the curly braces, and this code will run (aka execute) if the boolean expression evaluates to true.

Boolean Expressions

You might be wondering what a boolean expression is. Remember we talked about expressions in a previoius class. An expression can be evaluated to a result. For example the expression 6 + 5 can be evaluated to a result of 11. A boolean expression evaluates to true or false. Here is a boolean expression:

5 > (3+1)

Does this boolean expression evaluate to true, or false? Let's try it out by using it in an IF statement:

if( 5 > (3+1) ){
  console.log("Yup! The boolean expression evaluates to true, which is why this alert code is running right now!");

If the boolean expression in the IF statement above evaluates to true, then we'll see the alert box appear. If it doesn't, then all the code in between the curly braces is skipped, or ignored, by the browser.

I'd like to point out that a variable all by itself can be used for the boolean expression in an IF statement:

var doneWithHomework = true;


It's pretty common to see boolean expressions that consist soley of a variable name. This example is convenient because the data type of the variable is a boolean. But you could set the value of the variable to another data type and still use it like this in an IF statement. I'm going to defer this topic until the next lesson because I don't want you to get bogged down with it right now. If you are itching to get at it, you could look up 'truthy and falsey values in JavaScript'.

IF/ELSE Statements

In the example above, we only ran code (showing an alert) if the boolean expression evaluated to true. But we often want to run different code if the boolean expression evaluates to false. In that case we can use a slightly different form of an IF statement, known as an IF/ELSE statement. Here's the syntax for an IF/ELSE statement:

if(boolean expression goes here){

  // the code inside these curly braces
  // will run if the boolean expression
  // evaluates to TRUE

  // the code inside these curly braces
  // will run if the boolean expression
  // evaluates to FALSE


Let's make a little game program that uses an IF/ELSE:

var guess = prompt("Who was the first president of the U.S.?");

if( guess == "George Washington" ){
  alert("Correct! You win!");
  alert("Sorry, you lose!");

Hopefully you've watched the video, so you know what this program does. It's very important to note that the boolean expression uses two equal signs. Remember that a single equal sign is used to assign a value to a variable, and that's not what we want here. If we had used a single equal sign, then "George Washington" would be assigned to the 'guess' variable, which would wipe out what the user entered into the prompt window. Instead we use two equal signs, which is for comparing two values. There is a big difference between 'comparing' and 'assigning', and in math a single equal sign is often used for both. But in JavaScript we must distinguish between comparing and assiging, so we use one equal sign to assign a value to a variable and two equal signs for comparing. Both = and == are called operators, which we'll dig into in the next lesson. For now I should just mention that = is called the assignment operator (because it's used to assign a value to a variable), and == is called the equality operator (because it is used to compare two values to see if they are equal).

We've introduced another keyword in this form of IF statement, which is else. To verbalize the code here we can say, "if the user enters the correct answer, then we alert that they win, otherwise (or else) we alert that they have lost".

Formatting IF Statments by Indenting

Notice that in the previous code sample, we have two pairs of curly braces. The first pair encloses the code that will run if the boolean expression evaluates to true. The second pair of curly braces encloses the code that will run if the boolean expression evaluates to false. In IF statements, each pair of curly braces represents a code branch, which is sort of like the branches of a tree. Programmers also refer to the code inside a pair of curly braces as a code block. Depending on the boolean expression, our program may go down one code branch (and execute the code in it), or it may go down the other, but it can never execute the code in both branches.

Now notice that the code inside each branch is indented, which makes it easy to visualize where one code branch ends and another begins. IF everything was left aligned, then it would be difficult to visualize the separation of the code branches, and it would be very difficult to read. Please make sure you indent your code properly. You'll have less bugs, and when you do have bugs, it will be easier to spot them. And your fellow programmers won't loath working with you (at least not for your code formatting habits). No programmer wants to work with someone who writes sloppy code.

IF/ELSE-IF Statements

With IF and IF/ELSE statements you are only evaluating one boolean expression (another way to say this is that 'you are only evaluating one true/false condition'). In a previous code snippet we ask a user to enter the name of the first U.S. president. Our IF statement checks only one condition; whether or not the answer entered is true or false.

We can use another variation of an IF statement to deal with more than one possible condition. Let's say we ask the user to enter a color. If the color they enter is red, then our program does one thing. If the color they enter is blue, then our program does something else. And if the color they enter is yellow, our program does yet another thing. Finally, if they enter any other color (something other than red, blue, or yellow), our program does yet another thing.

Here's what that code might look like:

var color = prompt("Enter a color (use all lower case letters please - JS is case sensitive.");

if(color == "red"){
  alert("Ah yes, the color of roses!");
}else if(color == "blue"){
  alert("What's the matter? Not feeling well today?");
}else if(color == "yellow"){
  alert("That's hot!");
  alert("Not sure what to tell you, but you didn't enter 'red', 'blue', or 'yellow'.");

Notice that we are combining the else and if keywords here, and they are followed by a boolean expression in parenthesis. And that the final else (which does not include if next to it) does not include a boolean expression. The program will follow the branch that goes with the first boolean expression that evaluates to true. The code in the final branch will run if none of the prevsious boolean expressions evaluate to true.

Here is the basic structure and syntax for this form of IF statement:

if(first boolean expression goes here){
  // this code runs if the first boolean expression is true
}else if(second boolean expression goes here){

  // this code runs if the second boolean expression is true

  // this code runs if neither of the first nor the second 
  // boolean expressions are true

As mentioned, only one branch of code will execute, regardless of which variation of IF statement you use. Take a look at this code sample:

var age = 9;

if(age < 10){
  console.log("age is less than 10");
}else if(age < 20){
  console.log("age is less than 20");

In this example, both boolean expressions evaluate to true. If statements will execute the code branch for the first boolean expression that evaluates to true. So in this case an console.log message will display "age is less than 10". As long as the value of age variable is 9, the second code branch will never execute. So it's not a practical example, but it demonstrates the behavior of IF statements.

Testing Your Code

We've seen the complexity of IF statements grow throughout the course of this lesson. So I'd like to point out how important it is to test your code well. Never ever assume that your code works without testing it. And to test it make sure you experiment with it to get every code branch in an IF statement to execute. To demonstrate how to manually test your code, we'll create this simple program:

var age = prompt("Enter your age");

if(age < 18){
	alert("You are not an adult");
}else if(age < 40){
	alert("You are a young adult");
}else if(age < 65){
	alert("You are middle aged");
	alert("You are a senior citizen");

In order to properly test this code you should run it over and over and enter the following values in the prompt:

  • A number less than 18
  • The number 18
  • A number that is greater than 18 and less than 40
  • The number 40
  • A number that is greater than 40 and less than 65
  • The number 65
  • A number that is greater than 65
  • A negative number
  • invalid/garbage data

Notice the last two values in the list. It raises some interesting questions about how the program is supposed to behave. How should the program respond if a negative number is entered? What should happen if the user enters something other than a number? We don't have to answer these questions now, but I want to give you something to think about. The point is that you need to become very good at testing you work. After teaching programming programming for a few years, I have noticed that many students do not do this.

Controlling the Flow

It's absolutely mandatory for a programmer to understand how these variations of IF statements work. It takes some practice to get a feel for the nuances between them.

You can use variations of the IF statement to control the flow of your program. This will determine what lines of code run and which lines will not run when your program is used.

Understanding how to control the flow of a program is hugely important. But in order to know how to control the flow, you must understand the problem that you are trying to solve with your program. So make sure to take the time to understand the problem before you dive into writing the code.

NEXT LESSON: JavaScript Operators