Javascript If Statement
As your Javascript programs get more sophisticated you will need to make use
of conditional statements that allow your program to make decisions. Nearly all
other programming languages use conditionals and Javascript is no exception.
The If Statement is a way to make decisions based on a variable or
some other type of data. For example you might have a variable that stores the date. With
this tiny bit of information you could easily program a small script to print out
"Today is my Birthday!" whenever the day and month were equal to your birthday.
This lesson will teach you the basics of using an If Statement in Javascript.
Javascript If Statement Syntax
There are two major parts to an if statement: the conditional statement and the
code to be executed.
The conditional statement is a statement that will evaluate to either True or False. The most
common type of a conditional statement used is checking to see if something equals a value. An example would
be checking if the date equaled your birthday.
The code to be executed contains the Javascript code that will be executed only if the
If Statement's conditional statement was true. In this simple If Statement example
we print out a message if the variable we are checking is equal to 7.
Javascript Code:
<script type="text/javascript">
<!--
var myNum = 7;
if(myNum == 7){
document.write("Lucky 7!");
}
//-->
</script>
Display:
This simple example created myNum and set it to 7. We then checked
to see if myNum was equal to 7 "myNum == 7" in the If Statement's conditional
statement which evaluated to True.
Because the conditional statement was True the block of code associated
with our If Statement "document.write..." was executed, as you can see in the Display.
Javascript If Statement: Else
We already taught you how to execute code if a given condition is True, but what
if you want to execute another piece of code if something is False? The answer is
to use an extension to the If Statement; the Else clause.
The Else clause is executed when the conditional statement is False. Let's take our example
from above, add an Else clause and change the value of myNum so that our conditional
statement is False.
Javascript Code:
<script type="text/javascript">
<!--
var myNum = 10;
if(myNum == 7){
document.write("Lucky 7!");
}else{
document.write("You're not very lucky today...");
}
//-->
</script>
Display:
|