All programming languages allow you to make decisions, that is, they allow the program to follow a certain course of action depending on whether a particular condition is met. This is what gives programming languages their intelligence.
For example, in a situation where we use JavaScript code that is compatible only with version 4 or later browsers, the condition could be that the user is using a version 4 or later browser. If we discover that this condition is not met, then we could direct them to a set of pages that are compatible with earlier browsers.
Conditions are comparisons between variables and data, such as the following:
Is A bigger than B?
Is this X equal to Y?
Is M not equal to N?
For example, if the variable browserVersion held the version of the browser that the user was using, the condition would be
Is browserVersion greater than or equal to 4?
You'll notice that all of these questions have a yes or no answer—that is, they are Boolean-based and can only evaluate to true or false. How do we use this to create decision-making capabilities in our code? We get the browser to test whether the condition is true. If (and only if) it is true, we execute a particular section of code.
Let's look at another example. Recall from Chapter 1 the natural English instructions we used to demonstrate how code flows. One of these instructions for making a cup of coffee was
Has the kettle boiled? If so, then pour water into cup; otherwise, continue to wait.
This is an example of making a decision. The condition in this instruction is "Has the kettle boiled?" It has a true or false answer. If the answer is true, we pour the water into the cup. If it isn't true, we continue to wait.
In JavaScript, we can change the flow of the code's execution depending on whether a condition is true or false, using an if statement or a switch statement. We will look at these shortly, but first we need to introduce some new operators that are essential for the definition of conditions—comparison operators.
In the last chapter, we saw how mathematical functions, such as addition and division, were represented by symbols, such as + and /, called operators. We also saw that if we want to give a variable a value, we can assign to it a value or the result of a calculation using the equals sign (=), termed the assignment operator.
Decision-making also has its own operators, which allow you to test conditions. Comparison operators, just like the mathematical operators we saw in the last chapter, have a left-hand side (LHS) and a right-hand side (RHS), and the comparison is made between the two. The technical terms for these are the left operand and right operand. For example, the less than operator, with the symbol <, is a comparison operator. We could write 23 < 45, which translates as "Is 23 less than 45?" Here, the answer would be true. See Figure 3-1.
There are other comparison operators, the more useful of which are summarized in the following table:
Operator Symbol |
Purpose |
---|---|
== |
Tests if LHS is equal to RHS |
< |
Tests if LHS is less than RHS |
> |
Tests if LHS is greater than RHS |
<= |
Tests if LHS is less than or equal to RHS |
>= |
Tests if LHS is greater than or equal to RHS |
!= |
Tests if LHS is not equal to RHS |
We'll see these comparison operators in use in the next section when we look at the if statement.
Recall from Chapter 2 that operators have an order of precedence. This applies also to the comparison operators. The == and != comparison operators have the lowest order of precedence, and the rest of the comparison operators, <, >, <=, and >=, have an equal precedence.
All of these comparison operators have a precedence that is below operators, such as +, -, *, and /. This means that if you make a comparison such as 3 * 5 > 2 * 5, the multiplication calculations are worked out first, before their results are compared. However, in these circumstances, it's both safer and clearer if you wrap the calculations on either side inside parentheses, for example, (3 * 5) > (2 * 5). As a general rule, it's a good idea to use parentheses to ensure that the precedence is clear, or you may find yourself surprised by the outcome.
One very important point to mention is the ease with which the assignment operator (=) and the comparison operator (==) can be mixed up. Remember that the = operator assigns a value to a variable and that the == operator compares the value of two variables. Even when you have this idea clear, it's amazingly easy to put one equals sign where you meant to put two—it's a mistake I make all too often, even now.
We can store the results of a comparison in a variable, as shown in the following example:
var age = prompt("Enter age:", ""); var isOverSixty = parseInt(age) > 60; document.write("Older than 60: " + isOverSixty);
Here we obtain the user's age using the prompt() function. This returns, as a string, whatever value the user enters. We then convert that to a number using the parseInt() function we saw in the previous chapter and use the is-greater-than operator to see if it's greater than 60. The result (either true or false) of the comparison will be stored in the variable isOverSixty.
If the user entered 35, the document.write() on the final line will write this to the page:
Older than 60: false
If the user entered 61, this will be displayed:
Older than 60: true
The if statement is one you'll find yourself using in almost every program that is more than a couple of lines long. It works very much like our understanding of the word "if" in the English language. For example, we might say in English, "If the room temperature is more than 80 degrees Fahrenheit, then I'll turn the air conditioning on." In JavaScript, this would translate into something like this:
if (roomTemperature > 80) { roomTemperature = roomTemperature – 10; }
How does this work? (See Figure 3-2.)
Notice that the test condition is placed in parentheses and follows the if keyword. Also, note that there is no semicolon at the end of this line. The code to be executed if the condition is true is placed in curly braces on the line after the condition, and each of these lines of code does end with a semicolon.
The curly braces, {}, have a special purpose in JavaScript: they mark out a block of code. Marking out lines of code as belonging to a single block means that JavaScript will treat them all as one piece of code. If the condition of an if statement is true, JavaScript executes the next line or block of code following the if statement. In the preceding example, we have only one statement in the block of code, so we could equally as well have written
if (roomTemperature > 80) roomTemperature = roomTemperature – 10;
However, if you have a number of lines of code that you want to execute, you need the braces to mark them out as a single block of code. For example, a modified version of the example with three lines of code would have to include the braces.
if (roomTemperature > 80) { roomTemperature = roomTemperature – 10; alert("Its getting hot in here"); alert("Air conditioning switched on"); }
A particularly easy mistake to make is to forget the braces when marking out a block of code to be executed. Instead of the code in the block being executed when the condition is true, you'll find only the first line after the if statement is executed. However, the other lines will always be executed regardless of the outcome of the test condition. To avoid mistakes like these, it's a good idea to always use braces, even where there is only one statement. If you get into this habit, you'll be less likely to leave them out when they are actually needed.
Let's return to our temperature converter example from Chapter 2 and add some decision-making functionality. Enter the following code shown, and save it as ch3_examp1.htm.
<html> <body> <script language="JavaScript" type="text/javascript"> var degFahren = prompt("Enter the degrees Fahrenheit",32); var degCent; degCent = 5/9 * (degFahren - 32); document.write(degFahren + "\xB0 Fahrenheit is " + degCent + "\xB0 centigrade<br>"); if (degCent < 0) { document.write("That's below the freezing point of water"); } if (degCent == 100) document.write("That's the boiling point of water"); </script> </body> </html>
Load the page into your browser and enter 32 into the prompt box for the Fahrenheit value to be converted. With a value of 32, neither of the if statement's conditions will be true, so the only line written in the page will be that shown in Figure 3-3.
Now reload the page and enter 31 for the Fahrenheit value. This time we'll see two lines in the page, as shown in Figure 3-4.
Finally, reload the page again, but this time, enter 212 in the prompt box. The two lines shown in Figure 3-5 will appear in the page.
The first part of the script block in this page is taken from the example ch2_examp4.htm in Chapter 2. We declare two variables, degFahren and degCent. The variable degFahren is given an initial value obtained from the user with the prompt() function. Note the prompt() function returns a string value, which we then explicitly convert to a numerical value using the Number() function. The variable degCent is then set to the result of the calculation 5/9 * (degFahren - 32), which is our Fahrenheit to centigrade conversion calculation.
var degFahren = Number(prompt("Enter the degrees Fahrenheit",32)); var degCent; degCent = 5/9 * (degFahren - 32);
Then we write the result of our calculation to the page.
document.write(degFahren + "\xB0 Fahrenheit is " + degCent + "\xB0 centigrade<br>");
Now we come to the new code; the first of our two if statements.
This if statement has the condition that asks, "Is the value of the variable degCent less than zero?" If the answer is yes (true), the code inside the curly braces executes. In this case, we write a sentence to the page using document.write(). If the answer is no (false), the processing moves on to the next line after the closing brace. Also worth noting is the fact that the code inside the if statement's opening brace is indented. This is not necessary, but it is a good practice to get into because it makes your code much easier to read.
When trying out the example, we started by entering 32, so that degFahren will be initialized to 32. In this case, the calculation degCent = 5/9 * (degFahren - 32) will set degCent to 0. So, the answer to the question "Is degCent less than zero?" is false, because degCent is equal to zero, not less than zero. The code inside the curly braces will be skipped and never executed. In this case, the next line to be executed will be the second if statement's condition, which we'll talk about shortly.
When we entered 31 in the prompt box, degFahren was set to 31, so the variable degCent will be -0.55555555556. So how does our if statement look now? It evaluates to "Is –0.55555556 less than zero?" The answer this time is true, and the code inside the braces, here just a document.write() statement, executes.
Finally, when we entered 212, how did this alter our if statement? The variable degCent is set to 100 by the calculation, so the if statement now asks the question, "Is 100 less than zero?" The answer is false, and the code inside the braces will be skipped over.
In the second if statement, we evaluate the condition "Is the value of variable degCent equal to 100?"
if (degCent == 100) document.write("That's the boiling point of water");
There are no braces here, so if the condition is true, the only code to execute is the first line below the if statement. When we want to execute multiple lines in the case of the condition being true, then braces are required.
We saw that when degFahren is 32, degCent will be 0. So our if statement will be "Is 0 equal to 100?" The answer is clearly false, and the code won't execute. Again, when we set degFahren to 31, degCent will be calculated to be -0.55555555556, so "Is –0.5555556 equal to 100?" is also false, and the code won't execute.
Finally, when degFahren is set to 212, degCent will be 100. This time the if statement is "Is 100 equal to 100?" and the answer is true, so the document.write() statement executes.
As we have seen already, one of the most common errors in JavaScript, even for experts, is using one equals sign for evaluating, rather than the necessary two. Take a look at the following code extract:
if (degCent = 100) document.write("That's the boiling point of water");
This condition will always evaluate to true, and the code below the if statement will always execute. Worse still, your variable degCent will be set to 100. Why? Because a single equals sign assigns values to a variable; only a double equals sign compares values. The reason an assignment always evaluates to true is that the result of the assignment expression is the value of the right-hand side expression and this is the number 100, which is then implicitly converted to a boolean and any number besides 0 and NaN converts to true.
You should have a general idea of how to use conditions in if statements now, but how do we use a condition such as "Is degFahren greater than zero, but less than 100?" There are two conditions to test here. We need to test whether degFahren is greater than zero and whether degFahren is less than 100.
JavaScript allows us to use such multiple conditions. To do this we need to learn about three more operators, the logical operators AND, OR, and NOT. The symbols for these are listed in the following table.
Operator |
Symbol |
---|---|
AND |
&& |
OR |
|| |
NOT |
! |
Notice that the AND and OR operators are two symbols repeated: && and ||. If you type just one symbol, & or |, strange things will happen because these are special operators called bitwise operators used in binary operations—for logical operations we must always always use two.
After we have discussed the three logical operators, we'll take a look at how to use them in if statements, with plenty of practical examples. So if it seems a bit confusing on first read, don't panic. All will become clear. Let's look at how each of these works, starting with the AND operator.
Recall that we talked about the left-hand side (LHS) and the right-hand side (RHS) of the operator. The same is true with the AND operator. However, now the LHS and RHS of the condition are Boolean values (usually the result of a condition).
The AND operator works very much like our understanding of the word in English. For example, we might say, "If I feel cold and I have a coat, then I'll put my coat on." Here, the left-hand side of the "and" word is "Do I feel cold?" and this can be evaluated as true or false. The right-hand side is "Do I have a coat?" which again is evaluated to either true or false. If the left-hand side is true (I am cold) and the right-hand side is true (I do have a coat), then I put my coat on.
This is very similar to how the AND operator works in JavaScript. The AND operator actually produces a result, just as adding two numbers together produces a result. However, the AND operator takes two Boolean values (on its LHS and RHS) and results in another Boolean value. If the LHS and RHS conditions evaluate to true, the result will be true. In any other circumstance, the result will be false.
Following is a truth table of possible evaluations of left-hand sides and right-hand sides and the result when AND is used.
Left-Hand Side |
Right-Hand Side |
Result |
---|---|---|
true |
true |
true |
false |
true |
false |
true |
false |
false |
false |
false |
false |
Although the table is strictly speaking true, it's worth noting that JavaScript doesn't like doing unnecessary work. Well, who does! If the left-hand side is false, then even if the right-hand side does evaluate to true it won't make any difference to the final result—it'll still be false. So to avoid wasting time, if the left-hand side is false, JavaScript doesn't even bother checking the right-hand side and just returns a result of false.
Just like AND, OR also works in a similar way to our English language understanding of the word. For example, we might say that if it is raining or if it is snowing, then we'll take an umbrella. If either of the conditions "it is raining" or "it is snowing" is true, then we will take an umbrella.
Again, just like AND, the OR operator acts on two Boolean values (one from its left-hand side and one from its right-hand side) and returns another Boolean value. If the left-hand side evaluates to true or the right-hand side evaluates to true, the result returned is true. Otherwise, the result is false. The following table shows the possible results.
Left-Hand Side |
Right-Hand Side |
Result |
---|---|---|
true |
true |
true |
false |
true |
true |
true |
false |
true |
false |
false |
false |
As with the AND operator, JavaScript likes to avoid doing things that make no difference to the final result. If the left-hand side is true, then whether the right-hand side is true or false makes no difference to the final result—it'll still be true. So, to avoid work, if the left-hand side is true, the right-hand side is not evaluated, and JavaScript simply returns true. The end result is the same—the only difference is in how JavaScript arrives at the conclusion. However, it does mean you should not rely on the right-hand side of the OR operator to be executed.
In English we might say, "If I'm not hot, then I'll eat soup." The condition being evaluated is whether I'm hot. The result is true or false, but in this example we act (eat soup) if the result is false.
However, JavaScript is used to executing code only if a condition is true. So if we want a false condition to cause code to execute, we need to switch that false value to true (and any true value to false). That way we can trick JavaScript into executing code after a false condition.
We do this using the NOT operator. This operator reverses the logic of a result; it takes one Boolean value and changes it to the other Boolean value. So it changes true to false and false to true. This is sometimes called negation.
To use the NOT operator, we put the condition we want reversed in parentheses and put the ! symbol in front of the parentheses. For example
if (!(degCent < 100)) { // Some code }
Any code within the braces will be executed only if the condition degCent < 100 is false.
The following table details the possible results when using NOT.
Right-Hand Side |
Result |
---|---|
true |
false |
false |
true |
The previous section started by asking how we could use the condition "Is degFahren greater than zero, but less than 100?" One way of doing this would be to use two if statements, one nested inside another. Nested simply means that there is an outer if statement, and nested inside this is an inner if statement. If the condition for the outer if statement is true, then (and only then) the nested inner if statement's condition will be tested.
Using nested if statements, our code would be
if (degCent < 100) { if (degCent > 0) { document.write("degCent is between 0 and 100"); } }
This would work, but it's a little verbose and can be quite confusing. JavaScript offers a better alternative—using multiple conditions inside the condition part of the if statement. The multiple conditions are strung together with the logical operators we just looked at. So, the preceding code could be rewritten as the following:
if (degCent > 0 && degCent < 100) { document.write("degCent is between 0 and 100"); }
The if statement's condition first evaluates whether degCent is greater than 0. If that is true, the code goes on to evaluate whether degCent is less than 100. Only if both of these conditions are true will the document.write() code line execute.
In this example, we'll demonstrate multi-condition if statements using the AND, OR, and NOT operators. Type in the following code, and save it as ch3_examp2.htm.
<html> <body> <script language="JavaScript" type="text/javascript"> var myAge = Number(prompt("Enter your age",30)); if (myAge >= 0 && myAge <= 10) { document.write("myAge is between 0 and 10<br>"); } if ( !(myAge >= 0 && myAge <= 10) ) { document.write("myAge is NOT between 0 and 10<br>"); } if ( myAge >= 80 || myAge <= 10 ) { document.write("myAge is 80 or above OR 10 or below<br>"); } if ( (myAge >= 30 && myAge <= 39) || (myAge >= 80 && myAge <= 89) ) { document.write("myAge is between 30 and 39 or myAge is between 80 and 89"); } </script> </body> </html>
When you load it into your browser, you should see a prompt box appear. Enter the value 30, then press return, and the lines shown in Figure 3-6 are written to the web page.
We start the script block by defining the variable myAge and initializing it to the value entered by the user in the prompt box and converted to a number.
var myAge = Number(prompt("Enter your age",30));
After this we have four if statements, each using multiple conditions. We'll look at each in detail in turn.
The easiest way to work out what multiple conditions are doing is to split them up into smaller pieces and then evaluate the combined result. In our example we have entered the value 30, which has been stored in variable myAge. We'll substitute this value into the conditions to see how they work.
Here's the first if statement:
if (myAge >= 0 && myAge <= 10) { document.write("myAge is between 0 and 10<br>"); }
The first if statement is asking the question "Is myAge between 0 and 10?" We'll take the LHS of the condition first, substituting in our particular value for myAge. This asks "Is 30 greater than or equal to 0?" The answer is true. The question posed by the RHS condition is, "Is 30 less than or equal to 10?" The answer is false. These two halves of the condition are joined using &&, which indicates the AND operator. Using the AND results table shown earlier, we can see that if LHS is true and RHS is false, we have an overall result of false. So the end result of the condition for the if statement is false, and the code inside the braces won't execute.
Let's move on to the second if statement.
if ( !(myAge >= 0 && myAge <= 10) ) { document.write("myAge is NOT between 0 and 10<br>"); }
The second if statement is posing the question "Is myAge not between 0 and 10?" Its condition is similar to that of the first if statement, but with one small difference: we have enclosed our condition inside parentheses and put the NOT operator (!) in front.
The part of the condition inside the parentheses will be evaluated and, as before, produces the same result—false. However, the NOT operator reverses the result and makes it true. Because the if statement's condition is true, the code inside the braces will execute this time causing a document.write() to write a response to the page.
What about the third if statement?
if ( myAge >= 80 || myAge <= 10 ) { document.write("myAge is either 80 and above OR 10 and below<br>"); }
The third if statement asks, "Is myAge greater than or equal to 80, or less than or equal to 10?" Taking the LHS condition first—"Is 30 greater than or equal to 80?"—the answer is false. The answer to the RHS condition—"Is 30 less than or equal to 10?"—is again false. These two halves of the condition are combined using ||, which indicates the OR operator. Looking at the OR result table earlier in this section, we see that false OR false produces a result of false. So again the if statement's condition evaluates to false, and the code within the curly braces does not execute.
The final if statement is a little more complex.
if ( (myAge >= 30 && myAge <= 39) || (myAge >= 80 && myAge <= 89) ) { document.write("myAge is either between 30 and 39 " + "or myAge is between 80 and 89<br>"); }
It asks the question, "Is myAge between 30 and 39 or between 80 and 89?" Let's break the condition down into its component parts. We have a left-hand side and a right-hand side condition, combined using an OR operator. However, the LHS and RHS themselves have an LHS and RHS, which are combined using AND operators. Notice how we use parentheses to tell JavaScript which parts of the condition we want to be evaluated first, just as we would with numbers in a mathematical calculation.
Let's look at the LHS of the condition first, namely (myAge >= 30 && myAge <= 39). By putting the condition into parentheses, we ensure it's treated as a single condition; no matter how many conditions are inside the parentheses, it only produces a single result, either true or false. Breaking down the conditions in the parentheses, we have "Is 30 greater than or equal to 30?" with a result of true, and "Is 30 less than or equal to 39?" again with a result of true. From our AND table, we know true AND true produces a result of true.
Now let's look at the RHS of the condition, namely (myAge >= 80 && myAge <= 89). Again breaking the condition down, we see that the LHS asks, "Is 30 greater than or equal to 80?" which gives a false result, and the RHS asks, "Is 30 less than or equal to 89?" which gives a true result. We know that false AND true gives a false result.
Now we can think of our if statement's condition as looking like (true || false). Looking at our OR results table, we can see that true OR false gives a result of true, so the code within the braces following the if statement will execute, and a line will be written to the page.
However, remember that JavaScript does not evaluate conditions where they won't affect the final result, and the preceding condition is one of those situations. The LHS of the condition evaluated to true. After that, it does not matter if the RHS of the condition is true or false because only one of the conditions in an OR operation needs to be true for a true result. Thus JavaScript does not actually evaluate the RHS of the condition. We did so simply for demonstration purposes.
As we have seen, the easiest way to approach understanding or creating multiple conditions is to break them down into the smallest logical chunk. You'll find that with experience, you will do this almost without thinking, unless you have a particularly tricky condition to evaluate.
Although using multiple conditions is often better than using multiple if statements, there are times when it makes your code harder to read and therefore harder to understand and debug. It's possible to have 10, 20, or more than 100 conditions inside your if statement, but can you imagine trying to read an if statement with even 10 conditions? If you feel like your multiple conditions are getting too complex, break them down into smaller logical chunks.
For example, imagine we wanted to execute some code if myAge is in the ranges 30–39, 80–89, or 100–115. We could write the statement like so:
if ( (myAge >= 30 && myAge <= 39) || (myAge >= 80 && myAge <= 89) || (myAge >= 100 && myAge <= 115) ) { document.write("myAge is between 30 and 39 " + "or myAge is between 80 " + "and 89 or myAge is between 100 and 115"); }
There's nothing wrong with this, but it is starting to get a little long and difficult to read. Instead we could create another if statement for the 100–115 range part.
Imagine a situation where you want some code to execute if a certain condition is true, and some other code to execute if it is false. We can achieve this by having the two if statements, as shown in the following example:
if (myAge >= 0 && myAge <= 10) { document.write("myAge is between 0 and 10"); } if ( !(myAge >= 0 && myAge <= 10) ) { document.write("myAge is NOT between 0 and 10"); }
The first if statement tests whether myAge is between 0 and 10, and the second for the situation where myAge is not between 0 and 10. However, JavaScript provides an easier way of achieving this: by using an else statement. Again, the use of the word else is similar to its use in the English language. We may say, "If it is raining, I will take an umbrella, otherwise I will take a sun hat." In JavaScript we can say if the condition is true, then execute one block of code, else execute an alternative block. Rewriting the preceding code using this technique, we would have the following:
if (myAge >= 0 && myAge <= 10) { document.write("myAge is between 0 and 10"); } else { document.write("myAge is NOT between 0 and 10"); }
Writing the code like this makes it simpler and therefore easier to read. Plus it also saves JavaScript from testing a condition to which we already know the answer.
We could also include another if statement with the else statement. For example
if (myAge >= 0 && myAge <= 10) { document.write("myAge is between 0 and 10"); } else if ( (myAge >= 30 && myAge <= 39) || (myAge >= 80 && myAge <= 89) ) { document.write("myAge is between 30 and 39 " + "or myAge is between 80 and 89"); } else { document.write("myAge is NOT between 0 and 10, " + "nor is it between 30 and 39, nor is it between 80 and 89"); }
The first if statement checks whether myAge is between 0 and 10 and executes some code if that's true. If it's false, an else if statement checks if myAge is between 30 and 39 or 80 and 89, and executes some other code if it's true. Failing that, we have a final else statement, which catches the situation where the value of myAge did not trigger true in any of the earlier if conditions.
When using if and else if, we need to be extra careful with our curly braces to ensure that the if and else if statements start and stop where we expect, and we don't end up with an else that doesn't belong to the right if. This is quite tricky to describe with words—it's easier to see what I mean with an example.
if (myAge >= 0 && myAge <= 10) { document.write("myAge is between 0 and 10"); if (myAge = 5) { document.write("Your 5 years old"); } else { document.write("myAge is NOT between 0 and 10"); }
Notice I haven't indented the code. While it does not matter to JavaScript, it does make it more difficult for humans to read and hides the missing curly brace that should be before the final else statement.
Correctly formatted and with the missing bracket inserted, the code looks like this:
if (myAge >= 0 && myAge <= 10) { document.write("myAge is between 0 and 10"); if (myAge = 5) { document.write("Your 5 years old"); } } else { document.write("myAge is NOT between 0 and 10"); }
As you can see, as well as working now, it is also a lot easier to see which code is part of which if block.
Up to this point we have been looking exclusively at using comparison operators with numbers. However, they work just as well with strings. All that's been said and done with numbers applies to strings, but with one important difference. We are now comparing data alphabetically rather than numerically, so there are a few traps to watch out for.
In the following code, we compare the variable myName, which contains the string "Paul", with the string literal "Paul".
var myName ="Paul"; if (myName == "Paul") { alert("myName is Paul"); }
How does JavaScript deal with this? Well, it goes through each letter in turn on the LHS and checks it with the letter in the same position on the RHS to see if it's actually the same. If at any point it finds a difference, it stops, and the result is false. If after having checked each letter in turn all the way to the end and it confirms that they are all the same, it returns true. The condition in the preceding if statement will return true, and so we'll see an alert box.
However, string comparison in JavaScript is case-sensitive. So, "P" is not the same as "p". Taking the preceding example, but changing the variable myName to "paul", we find that the condition is false and the code inside the if statement does not execute.
var myName ="paul"; if (myName == "Paul") { alert("myName is Paul"); }
The >=, >, <=, and < operators work with strings as well as with numbers, but again it is an alphabetical comparison. So "A" < "B" is true, because A comes before B in the alphabet. However, JavaScript's case sensitivity comes into play again. "A" < "B" is true, but "a" < "B" is false. Why? Because uppercase letters are treated as always coming before lowercase letters. Why is this? Each letter has a code number in the ASCII and Unicode character set, and the code numbers for uppercase letters are lower than the code numbers for lowercase letters. This is something to watch out for when writing your own code.
The simplest way to avoid confusion with different cases is to convert both strings to either uppercase or lowercase before you compare them. This can easily be achieved using the toUpperCase() or toLowerCase() functions, which we'll cover in the next chapter.
We saw earlier how the if and else if statements could be used for checking various conditions; if the first condition is not valid, then another is checked, and another, and so on. However when you want to check the value of a particular variable for a large number of possible values, there is a more efficient alternative, namely the switch statement. The structure of the switch statement is given in Figure 3-7.
The best way to think of the switch statement is "Switch to the code where the case matches." The switch statement has four important elements:
The test expression is given in the parentheses following the switch keyword. In the previous example, we are testing using the variable myName. Inside the parentheses, however, we could have any valid expression.
Next we come to the case statements. It's the case statements that do the condition checking. To indicate which case statements belong to our switch statement, we must put them inside the curly braces following the test expression. Each case statement specifies a value, for example "Paul". The case statement then acts like if (myName == "Paul"). If the variable myName did contain the value "Paul", execution would commence from the code starting below the case: "Paul" statement and would continue to the end of the switch statement. This example has only two case statements, but you can have as many as you like.
In most cases, you just want the block of code directly underneath the relevant case statement to execute, and not all the code below the relevant case statement, including any other case statements. To achieve this, we put a break statement at the end of the code that we want executed. This tells JavaScript to stop executing at that point and leave the switch statement.
Finally we have the default case, which (as the name suggests) is the code that will execute when none of the other case statements matched. The default statement is optional; if you have no default code that you want to execute, you can leave it out, but remember that in this case, no code will execute if no case statements match. It is a good idea to include a default case, unless you are absolutely sure that you have all your options covered.
Let's take a look at the switch statement in action. The following example illustrates a simple guessing game. Type in the code and save it as ch3_examp3.htm.
<html> <body> <script language="JavaScript" type="text/javascript"> var secretNumber = prompt("Pick a number between 1 and 5:", ""); secretNumber = parseInt(secretNumber); switch (secretNumber) { case 1: document.write("Too low!"); break; case 2: document.write("Too low!"); break; case 3: document.write("You guessed the secret number!"); break; case 4: document.write("Too high!"); break; case 5: document.write("Too high!"); break; default: document.write("You did not enter a number between 1 and 5."); break; } document.write("<br>Execution continues here"); </script> </body> </html>
Load this into your browser and enter, for example, the value 1 in the prompt box. You should then see something like that shown in Figure 3-8.
If, on the other hand, you enter the value 3, you should see a friendly message letting you know that you guessed the secret number correctly, as shown in Figure 3-9.
First we declare the variable secretNumber and set it to the value entered by the user via the prompt box. Note that we use the parseInt() function to convert the string that is returned from prompt() to an integer value.
var secretNumber = prompt("Pick a number between 1 and 5:", ""); secretNumber = parseInt(secretNumber);
Next we create the start of the switch statement.
switch (secretNumber) {
The expression in parentheses is simply the variable secretNumber, and it's this number that the case statements will be compared against.
We specify the block of code encompassing our case statements using curly braces. Each case statement checks one of the numbers between 1 and 5, because this is what we have specified to the user that she should enter. The first simply outputs a message that the number she has entered is too low.
case 1: document.write("Too low!"); break;
The second case statement, for the value 2, has the same message, so the code is not repeated here. The third case statement lets the user know that she has guessed correctly.
case 3: document.write("You guessed the secret number!"); break;
Finally, the fourth and fifth case statements output a message that the number the user has entered is too high.
case 4: document.write("Too high!"); break;
We do need to add a default case in this example, since the user might very well (despite the instructions) enter a number that is not between 1 and 5, or even perhaps a letter. In this case we add a message to let the user know that there is a problem.
default: document.write("You did not enter a number between 1 and 5."); break;
A default statement is also very useful for picking up bugs—if you have coded some of the case statements incorrectly, you will pick that up very quickly if you see the default code being run when it shouldn't.
We finally have added the closing brace indicating the end of the switch statement. After this we output a line to indicate where the execution continues.
} document.write("<br>Execution continues here");
Note that each case statement ends with a break statement. This is important to ensure that execution of the code moves to the line after the end of the switch statement. If we forget to include this, we could end up executing the code for each case following the case that matched.
You may have spotted a problem with the switch statement in our example—we want to execute the same code if the user enters a 1 or a 2, and the same code for a 4 or a 5. However, in order to achieve this, we have had to repeat the code in each case. What we would like is an easier way of getting JavaScript to execute the same code for different cases. Well, that's easy! Simply change the code so that it looks like this:
switch (secretNumber) { case 1: case 2: document.write("Too low!"); break; case 3: document.write("You guessed the secret number!"); break; case 4: case 5: document.write("Too high!"); break; default: document.write("You did not enter a number between 1 and 5."); break; }
If you load this into your browser and experiment with entering some different numbers, you should see that it behaves in exactly the same way as it did before.
Here, we are making use of the fact that if there is no break statement underneath the code for a certain case statement, execution will continue through each following case statement until a break statement or the end of the switch is reached. Think of it as a sort of free fall through the switch statement until we hit the break.
If the case statement for the value 1 is matched, execution simply continues until the break statement under case 2, so effectively we can execute the same code for both cases. The same technique is used for the case statements with values 4 and 5.