Control Statements
Control statements are designed to allow you to create scripts that can decide which lines of code are evaluated, or how many times to evaluate them. There are two different types of control statements: conditional statements and loop statements.
Control statements make their decisions based on an expression that evaluates to the logical values true or false or their equivalents in other data types. As we will be using non-boolean data types extensively for the remainder of the chapter, here is a reminder of how the other data types are treated in logical conditions:
Numbers are treated as true if not equal to 0, otherwise they are treated as false
Strings are treated as true if greater than 0 characters in length, otherwise they are treated as false
undefined is treated as false
null is treated as false
Conditional Statements
Conditional statements are used to make decisions. In real life, we make all sorts of decisions based on criteria such as "am I being offered enough money to take this job?" If the answer is "yes," then the result is "take the job." If the answer is "no," then "don't take the job." In JavaScript, you need to make decisions about which sections of code to evaluate. For example, if you asked a user for input so you could perform a calculation, you will want to carry out the calculation if the input is numeric, but not if it isn't.
You already have come across a simple means of making a decision in the form of the conditional operator, ?:. The conditional operator checks to determine if a condition is true or false, and uses the result to decide whether to evaluate to its second or third operand. Although this is a quick method of assigning one of two values to a variable, it is also very limited. If you want to choose between more than two options, the conditional operator is inadequate to do what you want.
The if, else, and else if Statements
The if, else, and else if statements allow you to make a choice among several options. First let's look at how to use the if statement to make a choice between two alternatives.
The if statement is the most frequently used decision-making statement. It checks a condition and if it evaluates to true, then the statement(s) that it governs are evaluated, but if it evaluates to false then the statement(s) are passed over. The syntax is as follows:
if (condition) statement
or
if (condition) statement
The condition is always surrounded by parentheses but the statement it governs can be on the same line or the following line. The JavaScript interpreter always associates the if statement with whatever statement follows it. Both code layouts work but some people prefer using separate lines because it makes their if statements easier to read. Here is an example that uses two if statements so you can get a feel for how the if statement works:
var myVar1 = true; var myVar2 = false; if (myVar1 == true) alert("myVar1 is true"); if (myVar2 == true) alert("myVar2 is true");
This will display only one alert box. The final line in the code will not cause an alert box to be displayed because the variable myVar2 has the value of false. See Figure 3.7.
Figure 3.7 The first if statement evaluates to true so the first alert box displays.
Remember that the comparison operator, ==, checks to see if the operands to its right and left are equal. If they are equal it returns true, and if they are not equal it returns false. In the above example, the condition for the first if statement evaluates to true because the value of myVar1 is true. The condition for the second statement evaluates to false because myVar2 does not equal true. As you can see, the if statement makes the decision as to whether the alert() function is called based on the evaluation of the condition.
Frequently, you will want the if statement (and the other conditional statements for that matter) to govern more than just one other statement. To do this, you need to use what is known as a statement block. The statement block consists of a pair of curly braces that surround the if statement's statements in the same way that curly braces surround the statements in the function body. For example:
if (condition) { statement1 statement2 ... statementN }
Hopefully this feels familiar. If the condition in parentheses evaluates to true, then the statements within the curly braces are evaluated. If the condition in parentheses evaluates to false, then none of those statements is evaluated.
TIP
It is useful to use curly braces even when the if statement has only one statement associated with it. Then if you later need to add other statements, you won't encounter errors caused by forgetting to add the curly braces.
Remember that conditional statements allow you to take one action if a condition is true and another if it isn't. This is where the else statement comes in. By placing the else statement after the if statement, it is linked to the if statement so that the statement(s) it governs is evaluated if the condition in the parentheses of the if statement turns out to be false. This saves writing out the condition again. In this way, either the statements the if statement governs will be evaluated, or the statements the else statement governs will be evaluated. After all a condition in JavaScript can only evaluate to true or false. Here are a couple of examples to demonstrate how you would write this:
if (4 < 3) alert("4 is less than 3"); else alert("4 is greater than 3");
Since 4 is greater than 3, the alert after the if statement is ignored; therefore, the alert() function after the else statement is evaluated. The else statement can also be used with a function block so you could write:
if (4 < 3) { alert("The if statement's statement block was evaluated"); alert("because 4 is less than 3"); } else { alert("The else statement's statement block was evaluated") alert("because 4 is greater than 3") }
Finally, when you need even more flexibility to check multiple conditions there is the else if statement. It is inserted between the if and else statements. Here's an example:
var promptVal = prompt("Please enter a number", ""); if (promptVal > 0) alert("The number you entered was positive"); else if (promptVal == 0) alert("The number you entered was zero"); else alert("The number you entered was negative");
In this example, the script accepts an inputted number and uses it along with the if ... else if ... else statements to choose among three possible alerts to evaluate. Note that only one of the control statements will be used. If the if statement's condition evaluates to true, then the else if statement and the else statement will be ignored. If the if statement evaluates to false, then the condition of the else if statement is checked. Likewise if the condition of the else if statement evaluated to true, then the else statement would be ignored. The else statement acts as the default if all the previous conditions evaluated to false. Sometimes you will not want anything to happen if none of your conditions evaluates to true, in which case you would not use an else statement.
Multiple else if statements can be placed between the if statement and else statement if you want to check for more than three conditions.
If you remember the discussion about the isNaN() function earlier, you may have realized that there is a problem with the example aboveit doesn't allow for the fact that the user may enter a non-numeric value. To accommodate this situation, you would want to move the condition checking for a number greater than 0 to an else if statement and use the if statement to first check if the value entered is numeric. To do this you would use the isNaN(). Here's an example:
var promptVal = prompt("Please enter a number", ""); if (isNaN(promptVal)) alert("That wasn't a number!"); else if (promptVal > 0) alert("The number you entered was positive"); else if (promptVal == 0) alert("The number you entered was zero"); else alert("The number you entered was negative");
Note that statement blocks also can be used with the else if statement to control more than just one statement, such as the alerts in the earlier example.
Let's look next at an alternative control statement, the switch statement, that could have been used instead of the if...else statements in the above example.
The switch Statement
The switch statement allows you to choose one of several options. It has functionality which resembles that provided by the if, else if, and else statements. Let's look at how the switch statement works.
The switch statement has markedly different syntax from the if...else statements, but it works in a similar way. Its structure is shown below. Note that the lines that begin with case must end in a colon.
switch (expression){ case value: statements case value: statements case value: statements }
NOTE
Case values in JavaScript do not need to be constants or the same data type.
The first thing a switch statement does is evaluate the expression contained within its parentheses to a single value. It then works its way down through the case statements checking if the value returned by the expression in parentheses after the switch keyword is matched by any of the values that follow the case keywords. If it finds a match, then it evaluates all the following statements that belong to that case statement.
Try the example in Listing 3.5, and see for yourself.
Listing 3.5 Switch Statement Demo (switchDemo.htm)
<html> <head> <title>Switch Statement Demo</title> <script language="javascript" type="text/javascript"> <!-- switch (1+1){ case "a": alert(1); case 2: alert(2); case true: alert(3); } //--> </script> </head> <body> <h1>Switch Statement Demo</h1> </body> </html>
This page will result in the alert boxes shown in Figure 3.8.
Figure 3.8 Two alert boxes are brought up because the second and third case statements each evaluate as true.
This is because the 1+1 evaluates to 2. Therefore it should come as no surprise that the first case, the string "a", does not cause the associated alert() function to be evaluated. But the next case is the number 2, which is a match. As you can see from the screenshots in Figure 3.8, this causes not only the alert containing the number 2 to be evaluated, but, perhaps surprisingly, the alert containing the number 3 is also displayed. However, this may come as no surprise. We did say that if a match was found all the following statements would be evaluated up to the closing curly brace of the switch statement. Although this feature can occasionally be of use, generally you will want to evaluate only the statements between the matching case and the following one. To do this, you need to use the break statement. Replace the switch statement in Listing 3.5 with the following code:
switch (1+1){ case "a": alert(1); break; case 2: alert(2); break; case 3: alert(3); break; }
NOTE
The statements following each case are not enclosed in curly braces as in a statement block even if there are lots of them on multiple lines. Therefore, it is helpful to lay out your code as shown in the example above, to help you or someone else decipher your code.
As you will see, using the break statement as the last statement in a case statement block breaks off evaluation of the switch statement, and execution of the script continues after the closing curly brace of the switch statement. This has the desired effect of preventing the statements belonging to the other case statements from being evaluated.
The switch statement is able, optionally, to run some code in the event that there are no matchesjust as a concluding else statement works at the end of an if...else statement. To do this, you would include, following the case statements, the keyword default followed by a colon, as shown in the example below:
switch ("Match this string."){ case "This doesn't match.": alert("This would have alerted if it had!"); break; case "Nor does this.": alert("This would have alerted if it had!"); break; case "Or this.": alert("This would have alerted if it had!"); break; default: alert("None of the cases matched so the default evaluated."); break; }
As none of the cases above are the string "Match this string", their statements are ignored and the statements under the default are evaluated. See Figure 3.9.
Figure 3.9 The default statement is evaluated when none of the case statements match.
So which should be used: the if...else statement or the switch statement? The answer is that often either will do. The switch statement checks for a match to a single expression, and therefore is useful when you need to evaluate different statements based on the value of a single variable. It is also more efficient, so try to become accustomed to using it when possible. The if...else statement, on the other hand, can be given a new condition to check with each else if statement. This gives the if statement (and its associated else if statements) more flexibility, so the if statement tends to be used more than the switch statement.