Working with Numbers
We can manipulate numbers by combining them with operators to form mathematical expressions, and by calling built-in functions to perform complex mathematical operations.
Using Operators
Basic arithmetic—addition, subtraction, multiplication, and division—is accomplished 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 toxx = 1 + 2 - 3 / 4; // Assign the value 2.25 toxx = 56; y = 4 * 6 + x; // Assign the value 80 toyy = x + (x * x) / x; // Assign the value 112 toy
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 ofxMath.min(x, y) // The smaller of the valuesxandyMath.pow(x, y) //xraised to the poweryMath.round(x) //xrounded to the nearest integer
The math functions return values that we use in expressions, just as
we use real numbers. For example, suppose we want to simulate a
six-sided die. We can use the
random( )
function to retrieve a random float between
and 1:
dieRoll = Math.random( );
Then we multiply that value by 6, giving us a float between and 5.999, to which we add 1: ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access