Java Reference
In-Depth Information
For example, in a situation in which you 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 you discover
that this condition is not met, you could direct him 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
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 this:
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 you use this to create decision-making capabilities in
your code? You get the browser to test for whether the condition is true. If (and only if) it is true, you
execute a particular section of code.
Look at another example. Recall from Chapter 1 the natural English instructions used to demonstrate
how code fl ows. One of these instructions for making a cup of coffee is:
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, you pour the water into the cup. If it isn't true, you
continue to wait.
In JavaScript, you can change the fl ow of the code's execution depending on whether a condition is
true or false, using an if statement or a switch statement. You will look at these shortly, but fi rst we
need to introduce some new operators that are essential for the defi nition of conditions — comparison
operators .
Comparison Operators
In Chapter 2 you saw how mathematical functions, such as addition and division, were represented by
symbols, such as plus (+) and forward slash (/), called operators. You also saw that if you want to give
a variable a value, you 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 enable you to test conditions. Comparison operators,
just like the mathematical operators you 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 the right operand. For example, the less-than operator, with the symbol <, is a compari-
son operator. You could write 23 < 45, which translates as “Is 23 less than 45?” Here, the answer would
be true (see Figure 3-1).
Search WWH ::




Custom Search