JavaScript Math Object
In this JavaScript tutorial, you will learn about Math Object, usage, properties and methods of math object along with syntax and examples.
Usage of Math Object:
JavaScript Math object is used to perform mathematical tasks. But unlike the String and the Date object which requires defining the object, Math object need not be defined. Math object in JavaScript has two main attributes:
- Properties
- Methods
Properties of Math Object:
The JavaScript has eight mathematical values and this can be accessed by using the Math Object. The eight mathematical values are:
- E
- PI
- square root of 2 denoted as SQRT2
- square root of 1/2 denoted as SQRT1_2
- natural log of 2 denoted as LN2
- natural log of 10 denoted as LN10
- base-2 log of E denoted as LOG2E
- base-10 log of E denoted as LOG10E
The way of accessing these values in JavaScript is by using the word Math before these values namely as
- Math.E
- Math.LOG10E and so on
Methods of Math Object:
There are numerous methods available in JavaScript for Math Object. Some of them are mentioned below namely:
- 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.
- round(x) – Rounds x up or down to the nearest integer. It rounds .5 up.
- 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.
Example for Math Object methods mentioned above:
|
The output of the above program is
6
This is because the round() method rounds the number given in argument namely here 5.8 to the nearest integer. It rounds .5 up which gives 6.
Another example for using Math Object in JavaScript.
|
Output of the above program is
9
3
-2
The above example uses the max() method of the Math object which returns the largest of the two numbers given in arguments of the max method.