JavaScript If Statements

When you write code, you will often need to use conditional statements.

A conditional statement refers to a piece of code that does one thing based on one condition, and another based on another condition. In fact, you could have as many conditions as you like.

JavaScript If statements are an example of conditional statements. With If statements, you can tell the browser to execute a piece of code only if a given condition is true.

Example If statement:

CodeResult

Favorite Color

Blue
Red
Green

Explanation of code

To create a JavaScript If statement

  1. Start with the word "if"
  2. Between open and closed brackets, write the actual condition that is being tested (i.e. if something is equal to something else).
  3. Between open and closed curly brackets (or braces), specify what will happen if the condition is satisfied.

JavaScript If Else statement

The above code is OK if you only want to display something when the condition is true. But what if you want to display something when the condition is not true. For example, what if the variable myColor was equal to, say, Red?

This is where an If Else statement comes in handy. The else part is what we're interested in here. The else is what tells the browser what to do if the condition is not true.

Example If Else statement:

CodeResult

Favorite Color

Blue
Red
Green
None

Explanation of code

The first part of this code is the same as the previous example. The second part is where we specify what to do if the condition is not true. Therefore, you write else followed by what you want to occur, surrounded by curly braces.

  1. Write an if statement (as per first example)
  2. Follow this with the word "else"
  3. Between open and closed curly brackets (or braces), specify what to do next.

JavaScript If Else If statement

The If Else If statement is more powerful than the previous two. This is because you can specify many different outputs based on many different conditions - all within the one statement. You can also end with an "else" to specify what to do if none of the conditions are true.

Example If Else If statement:

CodeResult

Favorite Color

Blue
Red
Green
None

Explanation of code

We started with an if and ended with an else, however, in the middle, we used an else if statement to specify what to do if the myColor variable was equal to Red. This statement looks exactly like the if statement - just with an else prepended to it.

By the way, we could have specified as many else if conditions as we liked.

If you do have many "else if" conditions, you might consider using a JavaScript "Switch" statement. The Switch statement is explained in the next lesson.

Enjoy this page?