IF STATEMENTS

If statements test one or more conditions. The basic syntax is as follows:

if (condition) {
statement 1
statement 2
. . .
}

If the condition is true, the block of code contained in the curly braces {} following the condition is executed. If the condition is false, the first code statement following the closing curly brace is executed; in other words, the if statement is ignored, and the parser moves on to the next code statement. The following's an example of an if statement:

if (myTrash == full)
{
alert ("The Trash can is full!");
alert ("Empty the Trash!);
}

Note that there's no semicolon after the condition or after the closing curly brace, but there are semicolons after each statement in the code block. Also notice that the if condition (the part in the parentheses) uses the equality operator, and the statements in the code block (between the curly braces) use the assignment operator. If you mistakenly use the assignment operator in the if condition, such as the following:

if (myTrash = full)
{
alert ("The Trash can is full!");
alert ("Empty the Trash!);
}

in this case, the condition will always be true, and so the if statement will always be executed.

You don't have to use curly braces if there's only one statement in your code block, for example:

if (myVariable == 5) myOtherVariable = 25;

An if statement can be used alone, or it can be combined with an else or an else-if statement:

if (myVariable == 5)
{
myVariable = 15;
myOtherVariable = 25;
}
else
{
alert ("myVariable is not equal to 5");
alert ("Choose a new variable.");
}

By using an if/else-if statement, you can include three or more conditions in your statement, such as the following:

if (myAccountBalance == 0){
myTransfer = 100;
alert ("Funds transferred!");
} 
else if (myAccountBalance < 0) {
myTransfer = 200;
alert ("Overdrawn!");
}
else
alert ("Cruising!");