What You’ll Learn in This Lesson:
How to test conditions with the
if
statement
How to use comparison operators to compare values
How to use logical operators to combine conditions
How to use alternative conditions with
else
How to create expressions with conditional operators
How to test for multiple conditions
How to perform repeated statements with the
for
loop
How to use
while
and do...while
loops
How to create infinite loops (and why you shouldn’t)
How to escape from loops and continue loops
How to loop through an array’s properties
Statements in a JavaScript program generally execute in the order in which they appear, one after the other. Because this order isn’t always practical, most programming languages provide flow control statements that let you control the order in which code is executed. Functions, which you learned about in the preceding lesson, are one type of flow control; although a function might be defined first thing in your code, its statements can be executed anywhere in the script.
In this lesson, you’ll look at two other types of flow control in JavaScript: conditions, which allow a choice of different options depending on values that are tested, and loops, which allow statements to repeat based on certain conditions.
if
StatementOne of the most important features of a computer language is the capability to test and compare values and to perform different actions based on the results of the test or the values that are present. 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) alert("I 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 all on one line, as in the preceding example, you can use only a single statement as the action. However, you can also use multiple statements for the action by enclosing the entire if
statement in curly braces ({}
), as shown here:
if (a == 1) {
alert("I found a 1!");
a = 0;
}
This block of statements checks the variable a
once again. If the value of the variable matches 1
, it displays a message and sets a
to 0
.
It’s up to you, as a matter of personal style, whether you use the curly braces for single statements within flow control structures. Some people find it easier to read if all the flow control structures are clearly delineated through the use of curly braces no matter their length, and other developers are perfectly happy using a mix of single-line conditional statements and statements within braces. It doesn’t really matter which you use; just try to use them consistently for easier ongoing maintenance.
The action part of an if
statement can include any of the JavaScript statements you’ve already learned (and those you haven’t, 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 a
and 1
). These values can be variables, constants, or even expressions in themselves.
Note
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 also compare two constants, but there’s usually no reason to do this.)
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 that you saw in the preceding section is used to test whether the two values are equal.
Various conditional operators are 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
Caution
Be sure not to confuse the equality operator (==
) with the assignment operator (=
), even though they both might be read or referred to 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 programming (JavaScript or otherwise).
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 == "") alert("error!");
if (email == "") alert("error!");
Using a logical operator, you can combine them into a single statement:
if ((phone == "") || (email == "")) alert("Something Is 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 == "")) alert("Both Values Are Missing!");
In this case, the error message will be displayed only if both the email address and phone number variables are blank.
Note
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 true, the second is not evaluated because the condition (one or the other) has already been met. You can therefore use operators to improve the speed of your scripts.
A third logical operator is the exclamation point (!
), which means NOT. It can be used to invert an expression—in other words, make a true expression false and a false expression 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. You could also use the !=
(NOT EQUAL
) operator to simplify this statement:
if (phone != "") alert("phone is OK");
Both of the preceding statements will alert you if the phone
variable has a value assigned to it (that is, if it is not blank or null
).
Note
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
”—which is an impossibility in our universe. In this case, OR
(||
) should have been used to make a meaningful condition.
else
KeywordAn additional feature of the if
statement is the else
keyword. Much like its English-language counterpart, else
tells the JavaScript interpreter what to do if the condition in the if
statement isn’t met. 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 snippet 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, courtesy of the else
statement.
Note
Like the if
statement, else
can be followed either by a single action statement or by a number of statements, enclosed in braces.
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) ? (value if true) : (value if false);
This construction ends up assigning one of two values to the variable: one value if the condition is true, and another value 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 directly after the question mark (?
) will be used if the condition is true, and the value directly after the colon (:
) will be used if the condition is false. The colon and what follows represents the else
portion of the statement, were it written as an if...else
statement and, like the else
portion of the if
statement, it is optional.
These shorthand expressions can be used anywhere JavaScript expects a value. They provide a quick way to make simple decisions about values. As an example, here’s a quick way to display a grammatically correct message about a variable:
document.write("Found " + counter +
((counter == 1) ? " word." : " words."));
This prints 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.
You might, in fact, find that conditional expressions are not quicker or easier for you to use, and that is perfectly fine. You should, however, know what they look like and how to read them in case you encounter them in someone else’s code in the future.
if
and else
You now have all the pieces necessary to create a script using if
and else
statements to control flow. In Lesson 4, “Understanding JavaScript,” you created a simple script that displays the current date and time. You’ll use that knowledge here as you create a script that uses conditions to display a greeting that depends on the time: “Good morning,” “Good afternoon,” “Good evening,” or “Good day.” To accomplish this task, you can use a combination of several if
statements, like so:
if (hour_of_day < 10) {
document.write("Good morning.");
} else if ((hour_of_day >= 14) && (hour_of_day <= 17)) {
document.write("Good afternoon.");
} else if (hour_of_day >= 17) {
document.write("Good evening.");
} else {
document.write("Good day.");
}
The first statement checks the hour_of_day
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 be tested only if the preceding 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.”
To try the time and greeting example in a browser, you need an HTML file. In this case, you can keep the JavaScript code separate. Listing 23.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 23.1 The HTML File for the Time and Greeting Example
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Time Greet Example</title>
<meta name="viewport"
content="width=device-width, initial-scale=1">
</head>
<body>
<h1>Current Date and Time</h1>
<script src="timegreet.js"></script>
</body>
</html>
Listing 23.2 shows the complete JavaScript file for the time and greeting example. This uses the built-in Date
object functions to find the current date and store it in hour_of_day
, minute_of_hour
, and seconds_of_minute
variables, as you learned in the last lesson. Next, document.write
statements display the current time, and the if
and else
statements, introduced earlier, display an appropriate greeting.
Listing 23.2 A Script to Display the Current Time and a Greeting
// Get the current date
now = new Date();
// Split into hours, minutes, seconds
hour_of_day = now.getHours();
minute_of_hour = now.getMinutes();
seconds_of_minute = now.getSeconds();
// Display the time
document.write("<h2>");
document.write(hour_of_day + ":" + minute_of_hour +
":" + seconds_of_minute);
document.write("</h2>");
// Display a greeting
// open the paragraph
document.write("<p>");
// change the greetings
if (hour_of_day < 10) {
document.write("Good morning.");
} else if ((hour_of_day >= 14) && (hour_of_day <= 17)) {
document.write("Good afternoon.");
} else if (hour_of_day >= 17) {
document.write("Good evening.");
} else {
document.write("Good day.");
}
// close the paragraph
document.write("</p>");
To try this example, save this file as timegreet.js
and then load the timegreet.html
file into your browser. Figure 23.1 shows the results of this script.
switch
In Listing 23.2, you used several if...else
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="previous.html";
} else if (button=="home") {
window.location="home.html";
} else if (button=="back") {
window.location="menu.html";
}
Although using this construction is a logical way of doing things, this method can get messy if each if
statement has its own block of code with several statements in it. 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="previous.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 })—Braces enclose the contents of the
switch
statement, much as with 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—This statement is used to end each case to skip to the end of the
switch
. If break
is not included, statements in multiple cases might be executed, whether or not they match.
The default case—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.
Note
You can use multiple statements after each case
statement within the switch
structure and not just the single-line statements shown here. 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
.
One of the main benefits of using a switch
statement instead of an if...else
statement is readability: In one glance you know that all the conditional tests are for the same expression, and you can therefore focus on understanding the desired outcome of the conditional tests. But using a switch
statement is purely optional; you might find that you prefer if...else
statements, and there’s nothing wrong with that. Any efficiency gains in using a switch
statement instead of an if...else
statement will not be noticeable to human eyes, if any is even present at all. The bottom line is this: Use what you like.
for
LoopsThe for
keyword is the first tool to consider for creating loops, much as you saw in the preceding lesson, in the random number example. 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++) {
// more code
}
There are three parameters in the for
loop, each separated by semicolons:
Initial expression—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.
Condition—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.
Increment expression—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 might sound a bit confusing, but when you’re used to for
, 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 0
, and loops as long as the value of i
is less than 10
. The increment expression, i++
, adds 1 to the value of i
with each iteration of the loop. Because this happens at the end of the loop, the output will be nine lines of text.
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>");
Note
It’s a good style convention to use braces with every loop, whether it contains one statement or many statements. 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 what this loop does, you can add it to a <script>
section of an HTML document, as shown in Listing 23.3.
Listing 23.3 A Loop Using the for
Keyword
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Using a for Loop</title>
<meta name="viewport"
content="width=device-width, initial-scale=1">
</head>
<body>
<h1>Using a for Loop</h1>
<p>The following is the output of the <strong>for</strong> loop:</p>
<script>
for (i=1;i<10;i++) {
document.write("This is line " + i + "<br>");
}
</script>
</body>
</html>
This example displays a message containing the current value of the loop’s counter during each iteration. The output of Listing 23.3 is shown in Figure 23.2.
for
loop example.Notice that the loop was executed only nine times. This is because the conditional is i<10
—that is, i
is less than 10
. When the counter (i
) is incremented to 10
, the expression is no longer true. If you want the loop to count to 10
, you have to change the conditional; either i<=10
or i<11
will work fine.
The for
loop is traditionally used to count from one number to another, but 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, as described in the next section.
while
LoopsAnother keyword for loops in JavaScript is while
. Unlike for
loops, while
loops don’t necessarily use a variable to count. Instead, they continue to 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 thought that you could have done the same thing with a for
loop, and you’d be correct:
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, all in one line. 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 takes the least amount of typing.
do...while
LoopsJavaScript, like many other programming languages, includes 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, so the commands inside the loop will always execute at least one time. 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.
Note
As with the for
and while
loops, the do
...
while
can include a single statement without braces or a number of statements enclosed in braces.
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, you’ll look at infinite loops (to be avoided!) and the break
and continue
statements, which give you more control over the execution of your loops.
The for
and while
loops give you quite a bit of control over the loops. 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; the n
variable does. This creates an infinite loop, which means the loop will continue executing until the user stops it or until it generates an error of some kind—usually because the browser runs out of memory.
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 may cause crashes.
Obviously, you should avoid infinite loops. They can 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.
Note
Depending on the browser version in use, an infinite loop might even make the browser stop responding to the user because all the memory is used up. Be sure you provide an escape route from infinite loops and be sure to always test your work.
Occasionally, you might want to create a long-running and seemingly infinite loop deliberately. For example, you might want your program to execute until the user explicitly stops it or until you provide 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) {
//more code
}
Because the value true
is the conditional, this loop will always find its condition to be true.
There is a way out of a long-running and seemingly infinite loop. You can use the break
statement at some point during the loop to exit 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, and if it finds the value 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.
One more JavaScript statement is available to help you control the execution of 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] + "<br>");
}
This script uses a for
loop to print scores for 20 students, stored in the score
array (not shown here). 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.
Yet another type of loop is available in JavaScript. The for...in
loop is not as flexible as an ordinary for
or while
loop, but it is specifically designed to perform an operation on each property of an object.
For example, the built-in navigator
object contains properties that describe the user’s browser. You can use for...in
to display this object’s properties:
for (i in navigator) {
document.write("<p>Property: " + i + "<br>");
document.write("Value: " + navigator[i] + "</p>");
}
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.
One common use of loops is to work with arrays. Without loops, it can be very difficult to initialize arrays. The following script will prompt the user for a series of names. After all the names have been entered, it will display the list of names in a numbered list. First, initialize some variables:
names = new Array();
var 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. The prompt
statement acts like alert
, only it asks for user input rather than just displaying a message. Use a loop to repeat the prompt for each name. You want the user to enter at least one name, so a do...while
loop is ideal:
do {
next = prompt("Enter the Next Name", "");
if (next > " ") names[i] = next;
i = i + 1;
} while (next > " ");
Note
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 preceding statement, like so:
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 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 in which 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] + "</li>");
}
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 between opening and closing <li>
tags 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 23.4 shows the HTML file for this example, and Listing 23.5 shows the JavaScript file.
Listing 23.4 HTML to Prompt for Names and Display Them
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Loops Example</title>
<meta name="viewport"
content="width=device-width, initial-scale=1">
</head>
<body>
<h1>Loops Example</h1>
<p>Enter a series of names and JavaScript will display them
in a numbered list.</p>
<script src="loops.js"></script>
</body>
</html>
Listing 23.5 JavaScript to Prompt for Names and Display Them
// create the array
names = new Array();
var 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] + "</li>");
}
// close the list
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 23.3 shows what the final results should look like in a browser.
In this lesson, 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 the do...while
loops, and how to control loops further by using the break
and continue
statements. Finally, you looked at the for...in
loop for working with each property of an object.
Q. What happens if I compare two items of different data types (for example, a number and a string) in a conditional expression?
A. 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. 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.
Q. Why don’t I get a friendly error message if I accidentally use =
instead of ==
?
A. In some cases, using =
does 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
is assigned the value 1
. The if
statement is considered true, and the value of a
is lost.
The Workshop contains quiz questions and activities to help you solidify your understanding of the material covered. Try to answer all questions before looking at the “Answers” section that follows.
1. Which of the following operators means “is not equal to” in JavaScript?
!
!=
<>
2. What does the switch
statement do?
Tests a variable or expression for a number of different values
Turns a variable on or off
Makes ordinary if
statements longer and more confusing
3. Which type of JavaScript loop checks the condition at the end of the loop?
for
while
do...while
4. Within a loop, what does the break
statement do?
Crashes the browser
Starts the loop over
Escapes the loop entirely
5. The statement while (3==3)
is an example of which of the following?
A typographical error
An infinite loop
An illegal JavaScript statement
6. How would you write the statement “if J is 10, then M is 40” in JavaScript?
if (j == 10) m = 40;
if (j == 10) then m = 40;
if (j equals 10) m = 40;
if (j equals 10) then m = 40;
7. Which of these is a logical operator?
$$
&*
=
!
8. What does the following statement say in English?
Wilma = (Barney == 50) ? 44 : 29;
Wilma is 44 and Barney is 50 if Wilma is 29
Wilma is 44 if Barney is 50; otherwise, Wilma is 29
Wilma is 29 if Barny is 50, otherwise Wilma is 44.
Wilma is 29 less than Barney if Barney is 50; otherwise Wilma is 44.
9. What does the statement scooby++
mean in JavaScript?
The function scooby
subtracts 1 from the argument.
The function scooby
adds 1 to the argument.
The variable scooby
has 1 subtracted from its value.
The variable scooby
has 1 added to its value.
10. Why would you want to create an infinite loop?
To let the script run until the user stops it.
To let the script run until the computer ends it.
To let the script run until the server stops it.
You would never want to create an infinite loop.
Note
Just a reminder for those of you reading these words in the print or e-book edition of this book: If you go to www.informit.com/register and register this book (using ISBN 9780672338083), you can receive free access to an online Web Edition that not only contains the complete text of this book but also features an interactive version of this quiz.
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.
6. a. The statement would be written as follows:
if (j == 10)
m = 40;
7. d. JavaScript has the logical operators AND, OR, and NOT, written as &&
, ||
, and !
.
8. b. The statement says that Wilma is 44 if Barney is 50; otherwise, Wilma is 29.
9. d. This is an increment expression, and it means that scooby
will have 1 added to its value.
10. a. An infinite or long-running loop is usually created to let the script run until the user explicitly stops it or until a break
or continue
statement occurs.
Modify Listing 23.4 to sort the names in alphabetical order before displaying them. You can use the
sort
method of the Array
object, described in Lesson 22, “Using JavaScript Variables, Strings, and Arrays.”
Modify Listing 23.4 to prompt for exactly 10 names. What happens if you click the Cancel button instead of entering a name?