So far, all the JavaScript code that you have written has been executed unconditionally. When you wrote a sequence of statements, those statements were executed one after another, in order.
Many programming tasks, however, require conditional control, that is, the ability to react differently based upon some condition. For example, consider the task of assigning students letter grades. Depending upon what the student's average is, a different letter grade must be assigned (e.g., 90 to 100 is an A, 80 to 89 is a B, etc.). In this lesson, you will be introduced to the if statement which is used to perform such conditional execution in JavaScript. Based upon some condition, an if statement can choose among alternative sequences of code to execute, or even choose to execute no code at all.
Conditional execution refers to the ability to execute a
statement or sequence of statements only if some condition holds. The
simplest form of conditional statement involves only one possible
action. For example, displaying a message when the value of a variable
is "Grover". However, conditional execution can also
involve alternatives based on the same or related conditions. For
example, we might want to display one message if the variable is
"Grover" and another message if it isn't. This type of conditional
execution in JavaScript is performed using if
statements.
The following example uses an if statement to
greet Grover specially. Let's say we have gotten the name of the
visitor stored in a variable first_name. The symbol
== is used in JavaScript to test for equality
(remember, just one = is for assignments!).
if (first_name == "Grover") {
alert("Hello Grover, great to see you!");
}
The following example uses the other form of an if
statement to greet Grover and to be a bit hostile to everyone else.
if (first_name == "Grover") {
alert("Hello Grover, great to see you!");
} else {
alert("Who the heck is " + first_name + "?");
}
In the first example, an alert box is displayed only if the
condition (first_name == "Grover") holds. If the
condition does not hold, then nothing special happens: the next
JavaScript statement (if there is one) is evaluated.
The second example includes an else case which
specifies the action to be taken when the condition does not hold
(i.e., first_name is not equal to
"Grover"). Exactly one of the two statements will be
executed!
The general form of an if statement is as follows,
where the else part is optional:
if (BOOLEAN_TEST) {
STATEMENTS_IF_TRUE
} else {
STATEMENTS_IF_FALSE
}
(Remember the discussion about the data types that JavaScript can handle? We saw numbers and strings, time to discuss the third type, booleans.)
Booleans are logical values that are either
true or false. For example, the
expression (7 > 13) is false while the
expression (7 > 3) is true. Booleans are
useful in choosing whether the condition inside an if-statement is true or
not. There are three logic operators that apply on Booleans:
! means NOT, so !(7 < 13) is false;
&& means AND, so
(7 > 13) && (7 > 3) is false;
|| means OR, so (7 > 13) || (7 > 3)
is true;
Try an example here, testing whether a number is positive.
The test in an if statement can be any boolean
expression, that is, any expression that evaluates to either
true or false. Recall that the following
relational operators can be used to build boolean expressions:
==
|
equal to |
!=
|
not equal to |
<
|
less than |
<=
|
less than or equal to |
>
|
greater than |
>=
|
greater than or equal to |
Add an else case to the if statement
above so that it displays an appropriate message in the event that the
number is not positive. Test your modified page on various inputs and
list the results. What will be displayed when the number is 0?
In its simplest form, an if statement can decide
whether or not to execute a sequence of statements. For example, in
the first example of an if statement above, the code will
either display a message on the condition that the name is
"Grover", or otherwise it will do nothing at all. Using
an else case, an if statement can decide
between two alternative sections of code, as in the example where a
different message is displayed for "Grover" and any other
name.
There are situations, however, in which more than two alternatives must be considered. For example, suppose you were to write code for assigning letter grades in a class based on the student's final class average.
if (grade >= 90) {
letterGrade = "A";
} else if (grade >= 80) {
letterGrade = "B";
} else if (grade >= 70) {
letterGrade = "C";
} else if (grade >= 60) {
letterGrade = "D";
} else {
letterGrade = "F";
}
The term cascading refers to the way that control cascades
down the statement like water down a multi-tiered waterfall. The top-most
test is evaluated first, in this case (grade >= 90). If
this test succeeds, the corresponding statements are executed and the
whole statement is done. If not, control cascades down to the next
if test, in this case (grade >= 80). In
general, control cascades down the statement from one test to another
until one succeeds or the end of the statement is reached, possibly with a
final else.
Augment your example so that there are three possible messages displayed, identifying whether the number is positive, negative, or zero.
Despite the uniformity that internet browsers have brought to the world of computing, they do not all display the same page when presented with some HTML file. As a result, some HTML code might be “best viewed” with Internet Explorer while on Netscape the code needs some modification. So, web authors who want to make absolutely sure that their web page will be viewed perfectly on any browser have to write two or more different pages optimized for each browser. How do you make sure a particular viewer sees the right page, though?
The authors could ask viewers to choose which page to view based on
the browser they are using. Even better, web authors can detect which
browser the viewer is using and direct them to the appropriate page.
JavaScript provides a property called navigator.appName
that contains the browser's name.
var browser_name = navigator.appName;
It also provides the property window.location, which
can be used to redirect the browser to another page.
window.location="http://www.wellesley.edu";
Use the evaluation box below to verify that these commands work as we say. For a comprehensive description of other parameters that you can detect through Javascript look at this hyperlink.
Let's play a little game with the viewer. Write and test an
if statement that detects the viewer's browser and send
them to the competitor's web site. In other words, if the browser is
"Microsoft Internet Explorer", send them to
http://www.netscape.com. On the other hand, if the
browser is "Netscape" send them to
http://www.microsoft.com. Use the above Evaluation Box to
test your code. Of course, you will need to test your code on both
browsers in order to verify that it really works.
Another useful example is to generate different pronouns in a madlib based on the gender of the subject.
In the execution box below insert the statement that will generate use “his” if the person is male and “her” if the person is female.
Optional reading: Thau Chapter 3.
© Computer Science 110 Staff
This work is licensed under a Creative Commons License
Date Modified:
Wednesday, 23-Jan-2008 13:56:01 EST