Bookmark and Share

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.

Advertise on Tizag.com

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 can 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 be either True or False. The most common type of conditional statement used checks to see if something equals a value. An example would be checking if a date equals your birthday.

Below is a segment of JavaScript code that will be executed only if the If Statement's conditional statement is 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, 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:

Bookmark and Share




Found Something Wrong in this Lesson?

Report a Bug or Comment on This Lesson - Your input is what keeps Tizag improving with time!

Advertise Here

More Tutorials!
Microsoft Office Tutorials Artist Tutorials