The Math Object


© Muhammad Ali Shah


Skill Level: Beginner / Intermediate
Skills Required: Objects and Basic JavaScript


Abstract:

Mathematical functions like addition, subtraction, averages, etc. are inevitable if you are working on a page that has to compute something. JavaScript solves the problem by giving you a complete Math Object to carry out various functions easily. This article discusses the various properties and methods available to us.


The Predefined Math object:

The predefined Math object has properties and methods for mathematical constants and functions. You don't create a new Math object. Its already created for you, just as window and document objects. For example, the Math object's PI property has the value of pi (3.1415...), which you would use in an application as Math.PI. A simple function that can compute the area of a circle is given below:

function area (radius)
{
   var A = Math.PI * radius * radius;
   return A;
}

Similarly, standard mathematical functions are methods of Math. These include trigonometric, logarithmic, exponential, and other functions. For example, if you want to use the trigonometric function sine, you would write Math.sin(1.56).


Methods and Properties:

Method / Property Description
Math.E Napier Constant - e (2.718...)
Math.PI The value of pi (3.141...)
abs(x) Absolute value of x
sin(x), cos(x), tan(x) Trigonometric function's value where x is in radians
asin(x), acos(x), atan(x) Inverse trigonometric function's value where x is in radians
exp(x), log(x) Exponential and natural logarithm of x
ceil(x) Ceiling method returns the least integer greater than or equal to x.
floor(x) Returns the greatest integer less than or equal to x
min(x,y), max(x,y) Return minimum or maximum (respectively) of x and y
pow(x,y) Returns x raised to the power y
random() Returns a random number between 0 and 1
round(x) Rounds x to nearest integer
sqrt(x) Returns square root of x


Number Object: Alongwith the Math Object you will find the Number object quite useful for advanced tasks. The different properties of this object and their description is provided below:

Go To Page: 1 2


The copyright of the article The Math Object in JavaScript is owned by . Permission to republish The Math Object in print or online must be granted by the author in writing.

Post this Article to facebook Add this Article to del.icio.us! Digg this Article furl this Article Add this Article to Reddit Add this Article to Technorati Add this Article to Newsvine Add this Article to Windows Live Add this Article to Yahoo Add this Article to StumbleUpon Add this Article to BlinkLists Add this Article to Spurl Add this Article to Google Add this Article to Ask Add this Article to Squidoo





Property Description
Number.MAX_VALUE the largest representable number
Number.MIN_VALUE the smallest representable number
Number.NaN a special not a number value