How to code control statements
Like all programming languages, JavaScript provides control statements that let you control how information is processed in an application. This topic will get you started with the use of these statements. But first, you'll learn how to code conditional expressions because all of the control statements use them.
How to code conditional expressions
Figure 2-14 shows you how to code conditional expressions that use the six relational operators. A conditional expression returns a value of true or false based on the result of a comparison between two expressions. If, for example, the value of lastName in the first expression in the first table is "Harrison", the expression will return false. Or, if the value of rate in the last expression is 10, the expression will return true (because 10 / 100 is .1 and .1 is greater than or equal to 0.1).
If you want to determine whether a string value is a valid numeric value, you can use the global isNaN method. This is illustrated by the next set of examples. To use this method, you pass a parameter that represents the string value that should be tested. Then, this method returns true if the value can't be converted to a number or false if it can be converted.
To code a compound conditional expression, you use the logical operators shown in the second table in this figure to combine two conditional expressions. If you use the AND operator, the compound expression returns true if both expressions are true. If you use the OR operator, the compound expression returns true if either expression is true. If you use the NOT operator, the value returned by the expression is reversed. For instance, !isNaN returns true if the parameter is a number, so isNaN(10) returns false, but !isNaN(10) returns true.
Note that the logical operators in this figure are shown in their order of precedence. That is the order in which the operators are evaluated if more than one logical operator is used in a compound expression. This means that NOT operators are evaluated before AND operators, which are evaluated before OR operators. Although this is normally what you want, you can override this order by using parentheses.
In most cases, the conditional expressions that you use are relatively simple so coding them isn't much of a problem. In the rest of this chapter, you'll see some of the types of conditional expressions that are commonly used.
The relational operators
The syntax of the global isNaN method
isNaN(expression)
Examples of the isNaN method
isNaN("Harris") // Returns true since "Harris" is not a numberisNaN("123.45") // Returns false since "123.45" can be converted to a number
The logical operators in order of precedence
How the logical operators work
Description
Note
Figure 2-14 How to code conditional expressions