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.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?");
}
//-->
</script>
Display:
What stink bombs?
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.
0 comments:
Post a Comment