Categories:

The Math object

Programmers are often typecast as good mathematicians. While this is in fact the case with me, I doubt it applies to everyone (small joke). As the scene erupts in a sea of fury, lets just settle on the fact that every mathematician needs a calculator sometimes, or in the case of JavaScript, the Math object. Want to calculate "2.5 to the power of 8" or "Sin0.9" in your script? JavaScript's virtual calculator is what you need.

Below lists all of Math's object's properties and methods:

Properties

Properties Description
E The constant of E, the base of natural logarithms.
LN2 The natural logarithm of 2.
LN10 The natural logarithm of 10.
LOG2E Base 2 logarithm of E.
LOG10E Base 10 logarithm of E.
PI Returns PI.
SQRT1_2 Square root of 1/2.
SQRT2 Square root of 2.

Methods

Methods Description
abs(x) Returns absolute value of x.
acos(x) Returns arc cosine of x in radians.
asin(x) Returns arc sine of x in radians.
atan(x) Returns arc tan of x in radians.
atan2(y, x) Counterclockwise angle between x axis and point (x,y).
ceil(x) Returns the smallest integer greater than or equal to x. (round up).
cos(x) Returns cosine of x, where x is in radians.
exp(x) Returns ex
floor(x) Returns the largest integer less than or equal to x. (round down)
log(x) Returns the natural logarithm (base E) of x.
max(a, b) Returns the larger of a and b.
min(a, b) Returns the lesser of a and b.
pow(x, y) Returns Xy
random() Returns a pseudorandom number between 0 and 1. Example(s).
round(x) Rounds x up or down to the nearest integer. It rounds .5 up. Example(s).
sin(x) Returns the Sin of x, where x is in radians.
sqrt(x) Returns the square root of x.
tan(x) Returns the Tan of x, where x is in radians.

Let's have JavaScript solve some mathematical problems that have baffled mankind for ages:

//calculate e5
Math.exp(5)
//calculate cos(2PI)
Math.cos(2*Math.PI)

The "with" statement

If you intend to invoke Math multiple times in your script, a good statement to remember is "with." Using it you can omit the "Math." prefix for any subsequent Math properties/methods:

with (Math){
var x= sin(3.5)
var y=tan(5)
var result=max(x,y)
}

And with that the tutorial comes to a wrap. Have fun crunching some numbers!