Javascript if, else if, else (conditional control) Tutorial

In this Javascript tutorial we learn how to use if, else if and else statements to control the flow of our applications conditionally.

We cover the if statement, the else if ladder and the else catch all fallback, as well as the shorthand ternary operator ( ? : ).

We also cover how to evaluate multiple conditions inside a single conditional statement, and how to nest conditionals inside each other.

What are conditional control statements

Javascript allows us to control the flow of our program through expressions that evaluate certain conditions. Based on the results, Javascript will execute sections of code.

As an example, let’s consider an application with a dedicated area for its members. A user needs to provide login credentials before gaining access to the member part of the application.

If a user provides the correct credentials, they’re allowed into the member area. Otherwise, they will be given the option to try try again or reset their password, if they have forgotten it.

Based on this, we can imagine that the logic of our code would like something like this:

Example:
if username is the same as the db_username and
if the password is the same as the db_password
	redirect user to member area

otherwise
	if user forgot password
		then reset password
	or try again

This is an oversimplified example and the actual code won’t look like this, but it demonstrates how we can control the flow of the application through the use of conditional logic.

We control the flow of our program with the following statements, in combination with relational (comparison) and logical operators.

  • if
  • else if
  • else
  • switch

The if conditional statement

An if statement will evaluate if a condition is true. If the condition does prove true, it will execute the code defined inside its code block.

To write an if statement, we use the keyword if , followed by the condition to evaluate between open and close parentheses. Lastly, we add a code block with the execution code.

A code block is written by using left and right curly braces. Everything between the curly braces will be the code that gets executed if the condition proves true.

Syntax:
if (condition) {

  // code to execute if
  // condition is true

}

Note that an if statement is not terminated with a semicolon, the closing curly brace indicates to the translator that the statement has ended.

Example:
<script>

  var num = 10;

  if (num > 5) {

    document.write("num is greater than 5");
  }

</script>

In the example above, the if statement will evaluate if the number stored in the variable num is bigger than 5. If it is, the code in the if statement code block will be executed.

Multiple conditions inside a single if statement

We can also write multiple conditions inside a single if statement with the help of the logical operators && and | | .

The && operators will evaluate if one condition AND another is true. Both must be true before the code in the code block will execute.

Example:
<script>

  var num = 10;

  if (num > 5 && num < 50) {

    document.write("num is greater than 5 AND less than 50");
  }

</script>

In the example above, we evaluate if num is both bigger than 5 and smaller than 50. Both conditions prove true so the code in the code block executes.

The || operators will evaluate if one condition OR another is true. One of the conditions must be true before the code in the code block will execute.

Example:
<script>

  var num = 10;

  if (num > 5 || num < 10) {

    document.write("num is either less than 10 or greater than 5, or both");
  }

</script>

In the example above, we evaluate if num is bigger than 5 or smaller than 10. The value of num is 10 and so it’s not smaller than 10, so that part of the condition proves false. But, num is bigger than 5 so the code executes.

The else if conditional ladder

When we need to do multiple types of conditions, we can chain our if statements into an else if ladder.

The translator will move to evaluate each if statement in the ladder when it’s done with the previous one above.

To write an else if statement, we add another if statement below our first, separated by the else keyword.

Syntax:
if (condition) {

  // execution block

} else if (condition) {

  // execution block

}

The translator will only move on to the else if condition when evaluation of the first if statement has completed.

As an example, let’s consider a “Guess the mystery number” game.

Example:
<script>

  var num = 8;

  if (num == 10) {

    document.write("Correct, the mystery number is 10");

  } else if (num > 10) {

    document.write("You've guessed too high, try again");

  } else if (num < 10) {

    document.write("You've guessed too low, try again");
  }

</script>

In the var num we simulate a user input of 8. We’ll use num in the else if ladder to evaluate if the user has guessed correctly.

In the if statement, we check if the user guessed 10, which is the mystery number. If not, the translator will move to the else if statement and check if the user guessed anywhere above 10. If the user guessed below 10, the translator will move to the final else if statement.

We typically use else if statements when we can’t combine the conditions in a single if statement.

The else conditional fallback

The else conditional statement is a catch all statement used when all other conditions above it are not true. An else statement has no conditional code because it doesn’t evaluate anything.

Syntax:
if (condition) {

  // if execution block

} else if (condition) {

  // else if execution block

} else {

  // catch all other
  // cases execution
  // block

}

The else statement doesn’t need to be preceded by an else if statement, it will work just as well with only a single if statement above it.

Let’s modify our else if ladder example to only use an else statement.

Example:
<script>

  var num = 8;

  if (num == 10) {

    document.write("Correct, the mystery number is 10");

  } else {

    document.write("Sorry, you've guessed wrong. Try again");
  }

</script>

This time, we don’t give the user a hint that they’ve guessed too high or too low. We use the else statement to catch any guess that is not 10 and inform the user to try again.

The ternary conditional operator (? :)

When we have an if else statement with only single execution statements, we can use what’s known as the ternary operator as a shorthand method to write it.

To use the ternary operator, we write the condition between parentheses first, followed by a ? operator. Then, we write the single execution statement if the condition proves true, followed by the : operator. Finally, we write the single execution statement if the condition proves false and terminate the whole expression with a semicolon.

Syntax:
(condition) ? if_true_statement : if_false_statement;

Let’s consider the following if else statement.

Example:
var num = 8;

if (num == 10) {
  document.write("num == 10");
} else {
  document.write("num != 10");
}

In the example above, we simply evaluate if a number is 10 or not and print a message to the page. Let’s convert this into shorthand with the ternary operator.

Example:
<script>

  var num = 8;

  // condition    if true statement             if false statement
  (num == 10)  ?  document.write("num == 10") : document.write("num != 10");

</script>

It may seem confusing at first, especially if you’ve only been writing traditional if statements for a while, but with practice it becomes second nature.

It’s important to note that many Javascript developers do not like to use the ternary operator because it makes the code harder to read, especially for new developers. Some employers may even disallow its use altogether.

For this reason, we’ll only be using traditional if else statements throughout this tutorial course, but feel free to practice the ternary in case you come across it in the wild.

How to nest if, else if and else statements

We can nest our conditional statements inside each other. The translator will evaluate the conditions hierarchically, meaning it will move from the outside inwards.

To nest a conditional statement, we simply write it inside the execution block of another conditional statement.

Example:
<script>

  var has_mana = true;
  var is_casting = false;

  if (has_mana) {

    if (!is_casting) {

      document.write("Casting Fireball of Doom!");
    }
  }

</script>

In the example above, the outer if statement will check if a player has enough mana to cast a spell. If they do, the translator will evaluate the inner nested if statement and check if the player is not already casting a spell (note the ! in front of the boolean variable).

If the player is not already casting a spell, the inner if statement’s code is executed and the Fireball of Doom is on its way to destroy the Evil ZomBunny of Surprising Fluffyness.

Summary: Points to remember

  • Code in if and else if statements’ code blocks will only be executed if the condition evaluates to true.
  • Code in an else statement will always execute if any conditional statements above it prove false.
  • An else statement doesn’t have a condition to evaluate.
  • The ternary operator can only execute single statements for both its if and else portions.
  • We nest conditional statements by simply writing them inside other conditional statements.