Else If Statements

The if…else if statement is used to execute code based on multiple conditions. The syntax for an if…else if statement is as follows:

if (condition1) {
  // code to be executed if condition1 is true
} else if (condition2) {
  // code to be executed if condition2 is true
} else {
  // code to be executed if condition1 and condition2 are false
}

The if…else if statement will continue to evaluate conditions until it finds one that is true. If none of the conditions are true, the code inside the else statement will be executed.

Here is an example of an if…else if statement:


		

In this example, the first condition is x == 5. If the value of x is equal to 5, the code inside the first if statement will be executed. Otherwise, the next condition will be evaluated. The second condition is x == 10. If the value of x is equal to 10, the code inside the second if statement will be executed. Otherwise, the code inside the else statement will be executed.

Task

Run the above code and experiment with the code to get used to it.

JavaScript If Statements Summary

Here is a summary of the JavaScript if statements that were covered in this chapter:

  • An if statement is a conditional statement that is used to execute code based on a condition.
  • The else statement is used to execute code when the condition in the if statement is false.
  • The if…else if statement is used to execute code based on multiple conditions.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT