Jump to content

User:Moncur/07

Ka Wiktionary

7. Controlling Flow with Conditions and Loops

[wax ka badal]

The if Statement

[wax ka badal]

One of the most important features of a computer language is the capability to test and compare values. This allows your scripts to behave differently based on the values of variables, or based on input from the user.

The if statement is the main conditional statement in JavaScript. This statement means much the same in JavaScript as it does in English—for example, here is a typical conditional statement in English:

If the phone rings, answer it.

This statement consists of two parts: a condition (If the phone rings) and an action (answer it). The if statement in JavaScript works much the same way. Here is an example of a basic if statement:

if (a == 1) window.alert("Found a 1!");

This statement includes a condition (if a equals 1) and an action (display a message). This statement checks the variable a and, if it has a value of 1, displays an alert message. Otherwise, it does nothing.

If you use an if statement like the preceding example, you can use a single statement as the action. You can also use multiple statements for the action by enclosing them in braces ({}), as shown here:

if (a == 1) {
 window.alert("Found a 1!");
 a = 0;
}

This block of statements checks the variable a once again. If it finds a value of 1, it displays a message and sets a back to 0.

Conditional Operators

[wax ka badal]

The action part of an if statement can include any of the JavaScript statements you've already learned (and any others, for that matter), but the condition part of the statement uses its own syntax. This is called a conditional expression.

A conditional expression usually includes two values to be compared (in the preceding example, the values were a and 1). These values can be variables, constants, or even expressions in themselves.

By the Way
Either side of the conditional expression can be a variable, a constant, or an expression. You can compare a variable and a value, or compare two variables. (You can compare two constants, but there's usually no reason to.)

Between the two values to be compared is a conditional operator. This operator tells JavaScript how to compare the two values. For instance, the == operator is used to test whether the two values are equal. A variety of conditional operators is available:

  • == Is equal to
  • != Is not equal to
  • < Is less than
  • > Is greater than
  • >= Is greater than or equal to
  • <= Is less than or equal to
By the Way
Be sure not to confuse the equality operator (==) with the assignment operator (=), even though they both might be read as "equals." Remember to use = when assigning a value to a variable, and == when comparing values. Confusing these two is one of the most common mistakes in JavaScript programming.

Combining Conditions with Logical Operators

[wax ka badal]

Often, you'll want to check a variable for more than one possible value, or check more than one variable at once. JavaScript includes logical operators, also known as Boolean operators, for this purpose. For example, the following two statements check different conditions and use the same action:

if (phone == "") window.alert("error!");
if (email == "") window.alert("error!");

Using a logical operator, you can combine them into a single statement:

if (phone == "" || email == "") window.alert("Something's Missing!");

This statement uses the logical Or operator (||) to combine the conditions. Translated to English, this would be, "If the phone number is blank or the email address is blank, display an error message."

An additional logical operator is the And operator, &&. Consider this statement:

if (phone == "" && email == "") window.alert("Both are Missing!");

This statement uses && (And) instead of || (Or), so the error message will only be displayed if both the email address and phone number variables are blank. (In this particular case, Or is a better choice.)

Did you Know?
If the JavaScript interpreter discovers the answer to a conditional expression before reaching the end, it does not evaluate the rest of the condition. For example, if the first of two conditions separated by the && operator is false, the second is not evaluated. You can take advantage of this to improve the speed of your scripts.

The third logical operator is the exclamation mark (!), which means Not. It can be used to invert an expression—in other words, a true expression would become false, and a false one would become true. For example, here's a statement that uses the Not operator:

if (!($phone == "")) alert("phone is OK");

In this statement, the ! (Not) operator inverts the condition, so the action of the if statement is executed only if the phone number variable is not blank. The extra parentheses are necessary because all JavaScript conditions must be in parentheses. You could also use the != (Not equal) operator to simplify this statement:

if ($phone != "") alert("phone is OK");

As with the previous statement, this alerts you if the phone number field is not blank.

Did you Know?
The logical operators are powerful, but it's easy to accidentally create an impossible condition with them. For example, the condition (a < 10 && a > 20) might look correct at first glance. However, if you read it out loud, you get "If a is less than 10 and a is greater than 20"an impossibility in our universe. In this case, Or (||) should have been used.

The else Keyword

[wax ka badal]

An additional feature of the if statement is the else keyword. Much like its English equivalent, else tells the JavaScript interpreter what to do if the condition isn't true. The following is a simple example of the else keyword in action:

if (a == 1) {
 alert("Found a 1!");
 a = 0;
}
else {
 alert("Incorrect value: " + a);
}

This is a modified version of the previous example. This displays a message and resets the variable a if the condition is met. If the condition is not met (if a is not 1), a different message is displayed.

By the Way
Like the if statement, else can be followed either by a single action statement or by a number of statements enclosed in braces.

Using Shorthand Conditional Expressions

[wax ka badal]

In addition to the if statement, JavaScript provides a shorthand type of conditional expression that you can use to make quick decisions. This uses a peculiar syntax that is also found in other languages, such as C. A conditional expression looks like this:

variable = (condition) ? (true action) : (false action);

This assigns one of two values to the variable: one if the condition is true, and another if it is false. Here is an example of a conditional expression:

value = (a == 1) ? 1 : 0;

This statement might look confusing, but it is equivalent to the following if statement:

if (a == 1)
value = 1;
else
value = 0;

In other words, the value after the question mark (?) will be used if the condition is true, and the value after the colon (:) will be used if the condition is false. The colon represents the else portion of this statement and, like the else portion of the if statement, is optional.

These shorthand expressions can be used anywhere JavaScript expects a value. They provide an easy way to make simple decisions about values. As an example, here's an easy way to display a grammatically correct message about a variable:

document.write("Found " + counter + ((counter == 1) ? " word." : " words."));

This will print the message Found 1 word if the counter variable has a value of 1, and Found 2 words if its value is 2 or greater. This is one of the most common uses for a conditional expression.

Testing Multiple Conditions with if and else

[wax ka badal]

You can now create an example script using if and else. In [Hour 2], "Creating Simple Scripts," you created a script that displays the current date and time. This example will use conditions to display a greeting that depends on the time: "Good morning," "Good Afternoon," "Good Evening," or "Good Day". To accomplish this, you can use a combination of several if statements:

if (hours < 10) document.write("Good morning.");
else if (hours >= 14 && hours <= 17) document.write("Good afternoon.");
else if (hours > 17) document.write("Good evening.");
else document.write("Good day.");

The first statement checks the hours variable for a value less than 10—in other words, it checks whether the current time is before 10:00 a.m. If so, it displays the greeting "Good morning."

The second statement checks whether the time is between 2:00 p.m. and 5:00 p.m. and, if so, displays "Good afternoon." This statement uses else if to indicate that this condition will only be tested if the previous one failed—if it's morning, there's no need to check whether it's afternoon. Similarly, the third statement checks for times after 5:00 p.m. and displays "Good evening."

The final statement uses a simple else, meaning it will be executed if none of the previous conditions matched. This covers the times between 10:00 a.m. and 2:00 p.m. (neglected by the other statements) and displays "Good day."

The HTML File

[wax ka badal]

To try this example in a browser, you'll need an HTML file. We will keep the JavaScript code separate, so [Listing 7.1] is the complete HTML file. Save it as timegreet.html but don't load it into the browser until you've prepared the JavaScript file in the next section.

Listing 7.1. The HTML File for the Time and Greeting Example
<html>
<head><title>if statement example</title></head>
<body>
<h1>Current Date and Time</h1>
<p>
<script language="JavaScript" type="text/javascript"
src = "timegreet.js">
</script>
</p>
</body>
</html>

The JavaScript File

[wax ka badal]

[Listing 7.2] shows the complete JavaScript file for the time greeting example. This uses the built-in Date object functions to find the current date and store it in hours, mins, and secs variables. Next, document.write statements display the current time, and the if and else statements introduced earlier display an appropriate greeting.

Listing 7.2. A Script to Display the Current Time and a Greeting
// Get the current date
now = new Date();
// Split into hours, minutes, seconds
hours = now.getHours();
mins = now.getMinutes();
secs = now.getSeconds();
// Display the time
document.write("<h2>");
document.write(hours + ":" + mins + ":" + secs);
document.write("</h2>");
// Display a greeting
document.write("<p>");
if (hours < 10) document.write("Good morning.");
else if (hours >= 14 && hours <= 17) document.write("Good afternoon.");
else if (hours > 17) document.write("Good evening.");
else document.write("Good day.");
document.write("</p>");

To try this example, save this file as timegreet.js (or download it from this book's website) and then load the timegreet.html file into your browser. [Figure 7.1] shows the results of this script.

Using Multiple Conditions with switch

[wax ka badal]

In the previous example, you used several if statements in a row to test for different conditions. Here is another example of this technique:

if (button=="next") window.location="next.html";
else if (button=="previous") window.location="prev.html";
else if (button=="home") window.location="home.html";
else if (button=="back") window.location="menu.html";

Although this is a compact way of doing things, this method can get messy if each if statement has its own block of code with several statements. As an alternative, JavaScript includes the switch statement, which enables you to combine several tests of the same variable or expression into a single block of statements. The following shows the same example converted to use switch:

switch(button) {
case "next":
window.location="next.html";
break;
case "previous":
window.location="prev.html";
break;
case "home":
window.location="home.html";
break;
case "back":
window.location="menu.html";
break;
default:
window.alert("Wrong button.");
}

The switch statement has several components:

  • The initial switch statement. This statement includes the value to test (in this case, button) in parentheses.
  • Braces ({ and }) enclose the contents of the switch statement, similar to a function or an if statement.
  • One or more case statements. Each of these statements specifies a value to compare with the value specified in the switch statement. If the values match, the statements after the case statement are executed. Otherwise, the next case is tried.
  • The break statement is used to end each case. This skips to the end of the switch. If break is not included, statements in multiple cases might be executed whether they match or not.
  • Optionally, the default case can be included and followed by one or more statements that are executed if none of the other cases were matched.
By the Way
You can use multiple statements after each case statement within the switch structure. You don't need to enclose them in braces. If the case matches, the JavaScript interpreter executes statements until it encounters a break or the next case.

Using for Loops

[wax ka badal]

Loops are useful any time you need a section of code to execute more than once. The for keyword is the first tool to consider for creating loops. A for loop typically uses a variable (called a counter or an index) to keep track of how many times the loop has executed, and it stops when the counter reaches a certain number. A basic for statement looks like this:

for (var = 1; var < 10; var++) {

There are three parameters to the for loop, separated by semicolons:

  • The first parameter (var = 1 in the example) specifies a variable and assigns an initial value to it. This is called the initial expression because it sets up the initial state for the loop.
  • The second parameter (var < 10 in the example) is a condition that must remain true to keep the loop running. This is called the condition of the loop.
  • The third parameter (var++ in the example) is a statement that executes with each iteration of the loop. This is called the increment expression because it is typically used to increment the counter. The increment expression executes at the end of each loop iteration.

After the three parameters are specified, a left brace ({) is used to signal the beginning of a block. A right brace (}) is used at the end of the block. All the statements between the braces will be executed with each iteration of the loop.

The parameters for a for loop may sound a bit confusing, but once you're used to it, you'll use for loops frequently. Here is a simple example of this type of loop:

for (i=0; i<10; i++) {
document.write("This is line " + i + "<br>");
}

These statements define a loop that uses the variable i, initializes it with the value of zero, and loops as long as the value of i is less than 10. The increment expression, i++, adds one to the value of i with each iteration of the loop. Because this happens at the end of the loop, the output will list the numbers zero through nine.

When a loop includes only a single statement between the braces, as in this example, you can omit the braces if you want. The following statement defines the same loop without braces:

for (i=0; i<10; i++)
document.write("This is line " + i + "<br>");
Did you Know?
It's a good style convention to use braces with all loops whether they contain one statement or many. This makes it easy to add statements to the loop later without causing syntax errors.

The loop in this example contains a document.write statement that will be repeatedly executed. To see just what this loop does, you can add it to a <script> section of an HTML document as shown in [Listing 7.3].

Listing 7.3. A Loop Using the for Keyword
<html>
<head>
<title>Using a for Loop</title>
</head>
<body>
<h1>"for" Loop Example</h1>
<p>The following is the output of the
<b>for</b> loop:</p>
<script language="JavaScript" type="text/javascript">
for (i=1;i<10;i++) {
document.write("This is line " + i + "<br>");
}
</script>
</body>
</html>

This example displays a message with the loop's counter during each iteration. The output of [Listing 7.3] is shown in [Figure 7.2].

Notice that the loop was only executed nine times. This is because the conditional is i<10. When the counter (i) is incremented to 10, the expression is no longer true. If you need the loop to count to 10, you can change the conditional; either i<=10 or i<11 will work fine.

By the Way
You might notice that the variable name i is often used as the counter in loops. This is a programming tradition that began with an ancient language called Forth. There's no need for you to follow this tradition, but it is a good idea to use one consistent variable for counters. (To learn more about Forth, see the Forth Interest Group's website at www.forth.org.)

The structure of the for loop in JavaScript is based on Java, which in turn is based on C. Although it is traditionally used to count from one number to another, you can use just about any statement for the initialization, condition, and increment. However, there's usually a better way to do other types of loops with the while keyword, described in the next section.

Using while Loops

[wax ka badal]

Another keyword for loops in JavaScript is while. Unlike for loops, while loops don't necessarily use a variable to count. Instead, they execute as long as a condition is true. In fact, if the condition starts out as false, the statements won't execute at all.

The while statement includes the condition in parentheses, and it is followed by a block of statements within braces, just like a for loop. Here is a simple while loop:

while (total < 10) {
n++;
total += values[n];
}

This loop uses a counter, n, to iterate through the values array. Rather than stopping at a certain count, however, it stops when the total of the values reaches 10.

You might have noticed that you could have done the same thing with a for loop:

for (n=0;total < 10; n++) {
total += values[n];
}

As a matter of fact, the for loop is nothing more than a special kind of while loop that handles an initialization and an increment for you. You can generally use while for any loop. However, it's best to choose whichever type of loop makes the most sense for the job, or that takes the least amount of typing.

Using do…while Loops

[wax ka badal]

JavaScript 1.2 introduced a third type of loop: the do…while loop. This type of loop is similar to an ordinary while loop, with one difference: The condition is tested at the end of the loop rather than the beginning. Here is a typical do…while loop:

do {
n++;
total += values[n];
}
while (total < 10);

As you've probably noticed, this is basically an upside-down version of the previous while example. There is one difference: With the do loop, the condition is tested at the end of the loop. This means that the statements in the loop will always be executed at least once, even if the condition is never true.

By the Way
As with the for and while loops, the do loop can include a single statement without braces, or a number of statements enclosed in braces.

Working with Loops

[wax ka badal]

Although you can use simple for and while loops for straightforward tasks, there are some considerations you should make when using more complicated loops. In the next sections, we'll look at infinite loops and the break and continue statements, which give you more control over your loops.

Creating an Infinite Loop

[wax ka badal]

The for and while loops give you quite a bit of control over the loop. In some cases, this can cause problems if you're not careful. For example, look at the following loop code:

while (i < 10) {
n++;
values[n] = 0;
}

There's a mistake in this example. The condition of the while loop refers to the i variable, but that variable doesn't actually change during the loop. This creates an infinite loop. The loop will continue executing until the user stops it, or until it generates an error of some kind.

Infinite loops can't always be stopped by the user, except by quitting the browser—and some loops can even prevent the browser from quitting, or cause a crash.

Obviously, infinite loops are something to avoid. They can also be difficult to spot because JavaScript won't give you an error that actually tells you there is an infinite loop. Thus, each time you create a loop in a script, you should be careful to make sure there's a way out.

By the Way
Depending on the browser version in use, an infinite loop might even make the browser stop responding to the user. Be sure you provide an escape route from infinite loops, and save your script before you test it just in case.

Occasionally, you might want to create an infinite loop deliberately. This might include situations when you want your program to execute until the user stops it, or if you are providing an escape route with the break statement, which is introduced in the next section. Here's an easy way to create an infinite loop:

while (true) {

Because the value true is the conditional, this loop will always find its condition to be true.

Escaping from a Loop

[wax ka badal]

There is one way out of an infinite loop. You can use the break statement during a loop to exit it immediately and continue with the first statement after the loop. Here is a simple example of the use of break:

while (true) {
n++;
if (values[n] == 1) break;
}

Although the while statement is set up as an infinite loop, the if statement checks the corresponding value of an array. If it finds a value of 1, it exits the loop.

When the JavaScript interpreter encounters a break statement, it skips the rest of the loop and continues the script with the first statement after the right brace at the loop's end. You can use the break statement in any type of loop, whether infinite or not. This provides an easy way to exit if an error occurs, or if another condition is met.

Continuing a Loop

[wax ka badal]

One more statement is available to help you control the execution of statements in a loop. The continue statement skips the rest of the loop but, unlike break, it continues with the next iteration of the loop. Here is a simple example:

for (i=1; i<21; i++) {
if (score[i]==0) continue;
document.write("Student number ",i, " Score: ", score[i], "\n");
}

This script uses a for loop to print out scores for 20 students, stored in the score array. The if statement is used to check for scores with a value of 0. The script assumes that a score of 0 means that the student didn't take the test, so it continues the loop without printing that score.

Looping Through Object Properties

[wax ka badal]

A third type of loop is available in JavaScript. The for…in loop is not as flexible as an ordinary for or while loop. Instead, it is specifically designed to perform an operation on each property of an object.

For example, the navigator object contains properties that describe the user's browser, as you'll learn in [Hour 15], "Unobtrusive Scripting." You can use for…in to display this object's properties:

for (i in navigator) {
document.write("property: " + i);
document.write(" value: " + navigator[i] + "<br>");
}

Like an ordinary for loop, this type of loop uses an index variable (i in the example). For each iteration of the loop, the variable is set to the next property of the object. This makes it easy when you need to check or modify each of an object's properties.

Try It Yourself: Working with Arrays and Loops

[wax ka badal]

To apply your knowledge of loops, you will now create a script that deals with arrays using loops. As you progress through this script, try to imagine how difficult it would be without JavaScript's looping features.

This simple script will prompt the user for a series of names. After all of the names have been entered, it will display the list of names in a numbered list. To begin the script, initialize some variables:

names = new Array();
i = 0;

The names array will store the names the user enters. You don't know how many names will be entered, so you don't need to specify a dimension for the array. The i variable will be used as a counter in the loops.

Next, use the prompt statement to prompt the user for a series of names. Use a loop to repeat the prompt for each name. You want the user to enter at least one name, so a do loop is ideal:

do {
next = prompt("Enter the Next Name", "");
if (next > " ") names[i] = next;
i = i + 1;
}
while (next > " ");
Did you Know?
If you're interested in making your scripts as short as possible, remember that you could use the increment (++) operator to combine the i = i + 1 statement with the previous statement: names[i++]=1.

This loop prompts for a string called next. If a name was entered and isn't blank, it's stored as the next entry in the names array. The i counter is then incremented. The loop repeats until the user doesn't enter a name or clicks Cancel in the prompt dialog.

Next, your script can display the number of names that was entered:

document.write("<h2>" + (names.length) + " names entered.</h2>");

This statement displays the length property of the names array, surrounded by level 2 heading tags for emphasis.

Next, the script should display all the names in the order they were entered. Because the names are in an array, the for…in loop is a good choice:

document.write("<ol>");
for (i in names) {
document.write("<li>" + names[i] + "<br>");
}
document.write("</ol>");

Here you have a for…in loop that loops through the names array, assigning the counter i to each index in turn. The script then prints the name with a <li> tag as an item in an ordered list. Before and after the loop, the script prints beginning and ending <ol> tags.

You now have everything you need for a working script. [Listing 7.4] shows the HTML file for this example, and [Listing 7.5] shows the JavaScript file.

Listing 7.4. A Script to Prompt for Names and Display Them (HTML)
<html>
<head>
<title>Loops Example</title>
</head>
<body>
<h1>Loop Example</h1>
<p>Enter a series of names. I will then
display them in a nifty numbered list.</p>
<script language="JavaScript" type="text/javascript"
src="loops.js">
</script>
</body>
</html>
Listing 7.5. A Script to Prompt for Names and Display Them (JavaScript)
// create the array
names = new Array();
i = 0;
// loop and prompt for names
do {
next = window.prompt("Enter the Next Name", "");
if (next > " ") names[i] = next;
i = i + 1;
} while (next > " ");
document.write("<h2>" + (names.length) + " names entered.</h2>");
// display all of the names
document.write("<ol>");
for (i in names) {
document.write("<li>" + names[i] + "<br>");
}
document.write("</ol>");

To try this example, save the JavaScript file as loops.js and then load the HTML document into a browser. You'll be prompted for one name at a time. Enter several names, and then click Cancel to indicate that you're finished. [Figure 7.3] shows what the final results should look like in a browser.

Summary

[wax ka badal]

In this hour, you've learned two ways to control the flow of your scripts. First, you learned how to use the if statement to evaluate conditional expressions and react to them. You also learned a shorthand form of conditional expression using the ? operator, and the switch statement for working with multiple conditions.

You also learned about JavaScript's looping capabilities using for, while, and other loops, and how to control loops further using the break and continue statements. Lastly, you looked at the for…in loop for working with each property of an object.

In the next hour, you'll look at JavaScript's built-in functions, another essential tool for creating your own scripts. You'll also learn about third-party libraries that enable you to create complex effects with simple scripts.

Q1
What happens if I compare two items of different data types (for example, a number and a string) in a conditional expression?
A1
The JavaScript interpreter does its best to make the values a common format and compare them. In this case, it would convert them both to strings before comparing. In JavaScript 1.3 and later, you can use the special equality operator === to compare two values and their types—using this operator, the expression will be true only if the expressions have the same value and the same data type.
Q2
Why would I use switch if using if and else is just as simple?
A2
Either one works, so it's your choice. Personally, I find switch statements confusing and prefer to use if. Your choice might also depend on what other programming languages you're familiar with because some support switch and others don't.
Q3
Why don't I get a friendly error message if I accidentally use = instead of ==?
A3
In some cases, this will result in an error. However, the incorrect version often appears to be a correct statement. For example, in the statement if (a=1), the variable a will be assigned the value 1. The if statement is considered true, and the value of a is lost.
Q4
It seems like I could use a for loop to replace any of the other loop methods (while, do, and so on). Why so many choices?
A4
You're right. In most cases, a for loop will work, and you can do all your loops that way if you want. For that matter, you can use while to replace a for loop. You can use whichever looping method makes the most sense for your application.

Quiz Questions

[wax ka badal]

Test your knowledge of JavaScript conditions and loops by answering the following questions.

1.
Which of the following operators means "is not equal to" in JavaScript?
  1. !
  2. !=
  3. <>
2.

What does the switch statement do?

  1. Tests a variable for a number of different values
  2. Turns a variable on or off
  3. Makes ordinary if statements longer and more confusing
3.
Which type of JavaScript loop checks the condition at the end of the loop?
  1. for
  2. while
  3. do…while
4.
Within a loop, what does the break statement do?
  1. Crashes the browser
  2. Starts the loop over
  3. Escapes the loop entirely
5.
The statement while (3==3) is an example of
  1. A typographical error
  2. An infinite loop
  3. An illegal JavaScript statement

Quiz Answers

[wax ka badal]
1. b. The != operator means is not equal to.
2. a. The switch statement can test the same variable or expression for a number of different values.
3. c. The do…while loop uses a condition at the end of the loop.
4. c. The break statement escapes the loop.
5. b. Because the condition (3==3) will always be true, this statement creates an infinite loop.

Exercises

[wax ka badal]

To further explore the JavaScript features you learned about in this hour, you can perform the following exercises:

  • Modify [Listing 7.4] to sort the names in alphabetical order before displaying them. You can use the sort method of the Array object, described in [Hour 5], "Using Variables, Strings, and Arrays."
  • Modify [Listing 7.4] to prompt for exactly 10 names. What happens if you click the Cancel button instead of entering a name?