Controlling JavaScript Program Flow
- Conditional Statements
- Loops and Control Structures
- How to Set and Use Timers
- Summary
- Q&A
- Workshop
- Exercises
Examines ways to recognize particular conditions and have your JavaScript program act in a prescribed way as a result.
Save 35% off the list price* of the related book or multi-format eBook (EPUB + MOBI + PDF) with discount code ARTICLE.
* See informit.com/terms
In previous lessons you took a quick trip through the data types that JavaScript variables can contain. To create anything but the simplest scripts, though, you’re going to need your code to make decisions based on those values. In this lesson we examine ways to recognize particular conditions and have our program act in a prescribed way as a result.
Conditional Statements
Conditional statements, as the name implies, are used to detect particular conditions arising in the values of the variables you are using in your script. JavaScript supports various such conditional statements, as outlined in the following sections.
The if() Statement
In the preceding lesson we discussed Boolean variables, which can take one of only two values—true or false.
JavaScript has several ways to test such values, the simplest of which is the if statement. It has the following general form:
if(this condition is true) then do this.
Let’s look at a trivial example:
var message = ""; var bool = true; if(bool) message = "The test condition evaluated to TRUE";
First, you declare a variable message and assign an empty string to it as a value. You then declare a new variable, bool, which you set to the Boolean value of true. The third statement tests the value of the variable bool to see whether it is true; if so (as in this case), the value of the variable message is set to a new string. Had you assigned a value of false to bool in the second line, the test condition would not have been fulfilled, and the instruction to assign a new value to message would have been ignored, leaving the variable message containing the empty string.
Remember, we said that the general form of an if statement is
if(this condition is true) then do this.
In the case of a Boolean value, as in this example, we have replaced the condition with the variable itself; since its value can only be true or false, the contents of the parentheses passed back to if accordingly evaluate to true or false.
You can test for the Boolean value false by using the negation character (!):
if(!bool) message = "The value of bool is FALSE";
Clearly, for !bool to evaluate to true, bool must be of value false.
Comparison Operators
The if() statement is not limited to testing the value of a Boolean variable; instead, you can enter a condition in the form of an expression into the parentheses of the if statement, and JavaScript will evaluate the expression to determine whether it is true or false:
var message = ""; var temperature = 60; if(temperature < 64) message = "Turn on the heating!";
The less-than operator (<) is one of a range of comparison operators available in JavaScript. Some of the comparison operators are listed in Table 10.1.
Table 10.1 JavaScript Comparison Operators
Operator |
Meaning |
== |
Is equal to |
=== |
Is equal to in both value and type |
!= |
Is not equal to |
> |
Is greater than |
< |
Is less than |
>= |
Is greater than or equal to |
<= |
Is less than or equal to |
How to Test for Equality
In the previous example, how could you test to see whether the temperature exactly equals 64 degrees? Remember that you use the equal sign (=) to assign a value to a variable, so this code won’t work as might be expected:
if(temperature = 64) ....
Were you to use this statement, the expression within the parentheses would be evaluated by JavaScript and the variable temperature would be assigned the value of 64. If this value assignment terminates successfully—and why shouldn’t it?—then the value assignment would return a value of true back to the if() statement, and the rest of the statement would therefore be executed. This isn’t the behavior you want at all.
Instead, to test for equality, you must use a double equal sign (==):
if(temperature == 64) message = "64 degrees and holding!";
More About if()
The previous examples carry out only a single statement when the test condition is met. What if you want to do more than this—for instance, carry out several statements?
To achieve this, you simply enclose in curly braces ({}) all the code statements that you want to execute if the condition is fulfilled:
if(temperature < 64) { message = "Turn on the heating!"; heatingStatus = "on"; // ... more statements can be added here }
You can also add a clause to the if statement that contains code you want to execute if the condition is not fulfilled. To achieve this, you use the else construct:
if(temperature < 64) { message = "Turn on the heating!"; heatingStatus = "on"; // ... more statements can be added here } else { message = "Temperature is high enough"; heatingStatus = "off"; // ... more statements can be added here too }
How to Test Multiple Conditions
You can use “nested” combinations of if and else to test multiple conditions before deciding how to act.
Let’s return to the heating system example and have it switch on the cooling fan if the temperature is too high:
if(temperature < 64) { message = "Turn on the heating!"; heatingStatus = "on"; fanStatus = "off"; } else if(temperature > 72){ message = "Turn on the fan!"; heatingStatus = "off"; fanStatus = "on"; } else { message = "Temperature is OK"; heatingStatus = "off"; fanStatus = "off"; }
The switch Statement
When you’re testing for a range of different possible outcomes of the same conditional statement, a concise syntax you can use is that of JavaScript’s switch statement:
switch(color) { case "red" : message = "Stop!"; break; case "yellow" : message = "Pass with caution"; break; case "green" : message = "Come on through"; break; default : message = "Traffic light out of service. Pass only with great care"; }
The keyword switch has in parentheses the name of the variable to be tested.
The tests themselves are listed within the braces, { and }. Each case statement (with its value in quotation marks) is followed by a colon and then the list of actions to be executed if that case has been matched. There can be any number of code statements in each section.
Note the break statement after each case. This jumps you to the end of the switch statement after having executed the code for a matching case. If break is omitted, it’s possible that more than one case will have its code executed.
The optional default case has its code executed if none of the specified cases were matched.
Logical Operators
Sometimes you want to test a combination of criteria to determine whether a test condition has been met, and doing so with if ... else or switch statements becomes unwieldy.
Let’s return once more to the temperature control program. JavaScript allows you to combine conditions using logical AND (&&) and logical OR (||). Here’s one way:
if(temperature >= 64 && temperature <= 72) { message = "The temperature is OK"; } else { message = "The temperature is out of range!"; }
You can read the preceding condition as “If the temperature is greater than or equal to 64 AND the temperature is less than or equal to 72.”
You can achieve exactly the same functionality using OR instead of AND:
if(temperature < 64 || temperature > 72) { message = "The temperature is out of range!"; } else { message = "The temperature is OK"; }
This example reverses the way to carry out the test; the conditional statement is now fulfilled when the temperature is out of range and can be read as “If the temperature is less than 64 OR greater than 72.”