On their own, the comparison and logical operators seem to be of little or no use. However, the ability to make decisions based on the current program state (conditional branching) is what separates computers from calculators and televisions. The simplest branching mechanism is the 'if' statement, whose syntax is:
Syntax: if(condition) Statement; |
The 'if' statement evaluates the condition, and if it's True, the statement is executed. If the condition is False, however, the statement is skipped and execution moves to the next statement in the program. The condition can be generated using the conditional and logical operators, providing a powerful means to alter program execution. For example, the following code produces the absolute value of a variable:
if(myVariable < 0) myVariable = -myVariable;
Often, your program code has to handle one condition one specific way, and handle all other cases another way. To accomplish this, the 'if' statement can also be constructed with the optional 'else' statement. The syntax for an if/else condition is:
Syntax: if(condition) Statement1; else Statement2; |
If the condition is True, Statement1 is executed. If the condition if False, Statement2 is executed.
A common use of this construct is in division. In JavaScript, attempting to divide by 0 will produce an error. To avoid producing this situation, you could use the following code:
If(denominator == 0) { alert("Attempting to divide by zero. Please try another value"); total = 0; } else total = numerator / denominator;
In this example, if the denominator is 0, we need to alert the user and avoid attempting to divide. In all other cases, we go ahead and perform the division. Notice that in the case where the denominator is 0, we actually need to execute two statements, so we have to group them together with brackets.
Sometimes, however, we have more than two cases that need to be handled. To accomplish this, we must use nested 'if' statements. The syntax for nested 'if' statements is:
Syntax: if(condition1) statement1; else if(condition2) statement2; . . . else if(condition_n) statement_n; else generic_case; |
By using nested 'if' statements, the conditions are mutually exclusive. Once one of the conditions has been satisfied, control will move to the next statement, past the 'generic_case' statement. If you use a series of 'if' statements without nesting them using the if/else syntax, each condition will be evaluated, and any condition that returns a True value will be executed.