Contact Our Development Team
Free Code Tutorials & Open Source Code
Decisions - if Statements
Tutorials > JavaScript > Decisions - IF Statements
The if Statement
We often need to execute different code depending on the value of a variable. To do this, we can use an if statement, the simplest form of which is:
if (condition) {
    //Do something.
}
In this case, JavaScript will evaluate 'condition' and determine whether it is true or false. If it is true, the code within the braces ({})will be executed. Otherwise, it will be ignored. The condition may be a variable, function, or arithmetic expression. For example:
x = 10;
y = 5;

if (x==y) {
    document.write("x is equal to y.");
}

if (x!=y) {
    document.write("x is not equal to y.");
}
Here, the output is:
x is not equal to y.

This code introduces two new comparison operators - == and != - 'is equal to' and 'not equal to' respectively. Comparison operations always result in either true or false. JavaScript supports the following comparison operators:

Operator Description Example
== is equal to 5==7 is false
!= is not equal to 5!=7 is true
> is greater than 5>7 is false
>= is greater than or equal to 5>7 is false
< is less than 5<7 is true
<= is less than or equal to 5<=7 is true
The if...else Statement
The basic if statement executes a block of code if the condition is true, and does nothing if it is false. The if...else statement expands on this, and executes one block of code if the condition is true, or another block if the condition is false. The example at the top of the page can be written more efficiently as:
x = 10;
y = 5;

if (x==y) {
    document.write("x is equal to y.");
} else {
    document.write("x is not equal to y.");
}
The result will be the same.
The if...else if...else Statement
This allows the selection of one of several blocks of code based on multiple conditions:
x = 15;

if(x>=100) {
    document.write("x is 3 digits or longer.");
} else if(x>=10) {
    document.write("x is a 2-digit number.");
} else if(x>0) {
    document.write("x is a single-digit number.");
} else {
    document.write("x is zero or negative.");
}
All three of these statements are in fact, different variations of the same basic if construct. In any if statement there must be exactly one if block, zero or more elseif blocks, and zero or one else blocks.
Page Responses
Currently there have been no responses to this page...
If you have anything to contribute to this tutorial, found a bug, or know a better way of achieving the same goal, please leave your response below.
     
Copyright ©2009, Wired IDS Ltd. | Licensed under Creative Commons Attribution Share-Alike | Load time: 0.296 seconds