
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
The String Type
|
83
Using Operators
Basic arithmetic—addition, subtraction, multiplication, and division—is accom-
plished using the +, –, *, and / operators. Operators can be used with any numeric
literals or data containers such as variables. Mathematical expressions are evaluated
in the order determined by the precedence of the operators, as shown in Table 5-1.
For example, multiplication is performed before addition. All of these are legitimate
uses of mathematical operators:
x = 3 * 5; // Assign the value 15 to x
x = 1 + 2 – 3 / 4; // Assign the value 2.25 to x
x = 56;
y = 4 * 6 + x; // Assign the value 80 to y
y = x + (x * x) / x; // Assign the value 112 to y
Built-in Mathematical Functions
To perform advanced math, we use the built-in mathematical functions of the Math
object. For example:
Math.abs(x) // Absolute value of x
Math.min(x, y) // The smaller of the values x and y
Math.pow(x, y) // x raised to the power y
Math.round(x) // x rounded to the nearest integer
These math functions return values that we use in expressions, just as we use literal
numbers. For example, suppose we want to simulate a six-sided die. We can use the
Math.random( ) function to retrieve a random float between 0 and 0.999...:
dieRoll = Math.random();
Then, we multiply that value by 6, giving us a float between ...