|
Free Open Book
Sams Teach Yourself JavaScript in 24 Hours |
Understanding Expressions and OperatorsAn expression is a combination of variables and values that the JavaScript interpreter can evaluate to a single value. The characters that are used to combine these values, such as + and /, are called operators. Did you Know? Along with variables and constant values, you can also use calls to functions that return results within an expression. Using JavaScript OperatorsYou've already used some operators, such as the + sign (addition) and the increment and decrement operators. Table 5.1 lists some of the most important operators you can use in JavaScript expressions.
Along with these, there are also many other operators used in conditional statementsyou'll learn about these in Hour 7, "Controlling Flow with Conditions and Loops." Operator PrecedenceWhen you use more than one operator in an expression, JavaScript uses rules of operator precedence to decide how to calculate the value. Table 5.1 lists the operators from lowest to highest precedence, and operators with highest precedence are evaluated first. For example, consider this statement: result = 4 + 5 * 3; If you try to calculate this result, there are two ways to do it. You could multiply 5 * 3 first and then add 4 (result: 19) or add 4 + 5 first and then multiply by 3 (result: 27). JavaScript solves this dilemma by following the precedence rules: Because multiplication has a higher precedence than addition, it first multiplies 5 * 3 and then adds 4, producing a result of 19. By the Way If you're familiar with any other programming languages, you'll find that the operators and precedence in JavaScript work, for the most part, the same way as those in C, C++, and Java. Sometimes operator precedence doesn't produce the result you want. For example, consider this statement: result = a + b + c + d / 4; This is an attempt to average four numbers by adding them all together and then dividing by four. However, because JavaScript gives division a higher precedence than addition, it will divide the d variable by 4 before adding the other numbers, producing an incorrect result. You can control precedence by using parentheses. Here's the working statement to calculate an average: result = (a + b + c + d) / 4; The parentheses ensure that the four variables are added first, and then the sum is divided by four. Did you Know? If you're unsure about operator precedence, you can use parentheses to make sure things work the way you expect and to make your script more readable. |
Main Menu |
| 500 Juegos Gratis | 500 Giochi Gratis | 500 Jeux Gratuits | 500 Jogos Gratis | 500 Kostenlose Spiele |