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.
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 web page. If you had 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?");
}
//-->
</script>
Display:
There are two important things to note about the Else If extension:
- 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.
- 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.
|