The if/else Structure
By Stephen Bucaro
The if or if/else structure can be used to provide flow control
in your Java Script code. Flow control determines which statements are executed
based upon the results of a test or condition. An if/else structure is
coded as shown below.
if(comparison)
{
statements;
}
else
{
statements;
}
The condition defined between the brackets frequently consists of a
Comparison operator which compares the values of two variables, or
compares the value of a variable to a constant value, as shown below.
if(x <= 100)
{
document.write("x is less than or equal to 100");
}
else
{
document.write("x is greater than 100");
}
The statement within the if brackets compares the value of a variable
named x to 100. If x is less than or equal to 100, the statement within
the first curly brackets is executed ("x is less than or equal to 100" is
printed). If x is greater than or 100, the statement within the second curly
brackets (following else is executed.
The if section is frequently used alone, without an accompanying
else section, as shown below.
if(x <= 100)
{
document.write("x is less than or equal to 100");
}
In this situation if the condition defined in the if statement is true,
the statement within the curly brackets is executed. If the condition defined in
the if statement is false, the program flow will continue with any code
after the if structure.
Within the curly brackets there can be any number of statements. The example
below shows two lines of code within each section, but it's possible to have
thousands of lines of codes within each section.
if(x <= 100)
{
document.write("x is less than or equal to 100");
x = x + 50;
}
else
{
document.write("x is greater than 100");
x = x - 50;
}
|