content logo

Learn Javascript:

Javascript Else If Statement

In the previous lesson, you learned how to create a basic If Statement in JavaScript, which is good enough for most programming situations. However, sometimes it is helpful to have the ability to check for more than one condition in a single If Statement block.

The Else If statement is an extension to the If Statement that allows you to create as many checks (conditional statements) as you want in one big block of If Statement code.

JavaScript Else If Example

Imagine that you want to have a small "student" script that will print out a customized message depending who is accessing the webpage. If you have more than two custom messages, you could use the Else If extension to solve this programming problem.

JavaScript Code:

<script type="text/javascript">
var visitor = "principal";

if(visitor == "teacher"){
	document.write("My dog ate my homework...");
}else if(visitor == "principal"){
	document.write("What stink bombs?");
} else {
	document.write("How do you do?");


What stink bombs?

There are two important things to note about the Else If extension:

  1. You must have a normal If Statement before you can use the Else If statement. This is because the Else If statement is an addon to the If Statement.
  2. You can have multiple Else If add-ons. In our example, we only used one Else If extension, but you can add as many as you require
#Javascript Else If Statement Example #Javascript Else If Statement Code #Javascript Else If Statement Tutorial