Search within TutorialsPark

Javascript Math Object


Learn to work with advanced math calculation using JavaScript Math Object


Javascript Math Object

The JavaScript Math object provides a common and easily accessible resource for mathematical formulas and informations.It enables users to work with advanced mathematical calculations like, logarithms, trignometry, roots , random numbers etc.

Calculations performed using Math Object get executed faster compared to the same task performed using regular JavaScript. It provides a number of properties and methods to perform such computations.

Math object is a built-in-object , hence you need not create an instance of Math object before using it using keyword new.


JavaScript Math Object: Constants and Simple Calculations.

The Math object stores a lot of mathematical constansts, like log values, PI. It can also be used to compute power and square roots of a number.

In the below demo, constants and some simple mathematical operations are performed using Math Object .

Example: Javascript Math Object : Constants and Simple Calculations.

Give it a TRY! » Note: The method Math.log() returns the natural Log of the Number to base E.


Javascript Math Object: Rounding off Numbers

The Math object provides methods of ceil(), floor() and round() to round off the numbers both upwards and downwards

All of these methods truncate the number provided as an argument to return a whole number rounded up based on the method used.

floor() : Method rounds numbers to the next lowest whole number, and then removes all values after decimal point.

ceil() : Method rounds numbers to the next largest whole number, and then removes all values after decimal point.

round() : Method rounds numbers to the next largest whole number for decimal values greater than .5 and to the lowest next integer for values less than 0.5.

Example: JavaScript Math Object : Rounding Off Numbers

Give it a TRY! » Note: Always use Math object instead of regular JavaScript Code.


Javascript Math Object: Generating Random Numbers

There is always a need to generate a random number to display some random image, message, ads etc in an unbaised way, for that very purpose we use Math.random() method.

The method Math.random() generates a random fraction number between 0 to 1, hence to have integer you should multiply it with integers and then truncate numbers after decimal point using Math.floor() method.

Example: JavaScript Math Object : Generate Random Numbers

Give it a TRY! » Note: Always use Math object instead of regular JavaScript Code.


Javascript Math Object: min() and max() Methods

The Math object provides methods of min() and max() are used to find the smallest and largest within a group of number.

Example: JavaScript Math Object : Generate Random Numbers

Give it a TRY! » Note: Always use Math object instead of regular JavaScript Code.