JavaScript Math Object

The JavaScript Math object allows you to perform mathematical tasks on numbers.

EXAMPLE ❯


The Math Object

Unlike other objects, the Math object has no constructor.

The Math object is static.

All methods and properties can be used without creating a Math object first.


Math Properties (Constants)

The syntax for any Math property is : Math.property.

JavaScript provides 8 mathematical constants that can be accessed as Math properties:

EXAMPLE ❯


Math Methods

The syntax for Math any methods is : Math.method(number)


Number to Integer

There are 4 common methods to round a number to an integer:

Math.round(x) Returns x rounded to its nearest integer
Math.ceil(x) Returns x rounded up to its nearest integer
Math.floor(x) Returns x rounded down to its nearest integer
Math.trunc(x) Returns the integer part of x 

Math.round()

Math.round(x) returns the nearest integer:

EXAMPLE ❯


Math.ceil()

Math.ceil(x) returns the value of x rounded up to its nearest integer:

EXAMPLE ❯


Math.floor()

Math.floor(x) returns the value of x rounded down to its nearest integer:

EXAMPLE ❯


Math.trunc()

Math.trunc(x) returns the integer part of x:

EXAMPLE ❯


Math.sign()

Math.sign(x) returns if x is negative, null or positive:

EXAMPLE ❯


Math.pow()

Math.pow(x, y) returns the value of x to the power of y:

EXAMPLE ❯


Math.sqrt()

Math.sqrt(x) returns the square root of x:

EXAMPLE ❯


Math.abs()

Math.abs(x) returns theabsolute (positive) value of x:

Example:

Math.abs(-4.7);     // returns 4.7


Math.sin()

Math.sin(x) returns the sine (a value between -1 and 1) of the angle x (given in radians).

If you want to use degrees instead of radians, you have to convert degrees to radians:

Angle in radians = Angle in degrees x PI / 180.

EXAMPLE ❯


Math.cos()

Math.cos(x) returns the cosine (a value between -1 and 1) of the angle x (given in radians).

If you want to use degrees instead of radians, you have to convert degrees to radians:

Angle in radians = Angle in degrees x PI / 180.

EXAMPLE ❯


Math.min() and Math.max()

Math.min() and Math.max() can be used to find the lowest or highest value in a list of arguments:

Min:

Math.min(01503020, -8, -200);  // returns -200

Max:

Math.max(01503020, -8, -200);  // returns 150

Example for Min & Max both:

EXAMPLE ❯


Math.random()

Math.random() returns a random number between 0 (inclusive), and 1 (exclusive):

You will learn more about Math.random() in the next chapter of this tutorial.

EXAMPLE ❯


The Math.log() Method

Math.log(x) returns the natural logarithm of x:

Example:

Math.log(1);    // returns 0

The natural logarithm returns the time needed to reach a certain level of growth.

Math.E and Math.log() are twins.

How many times must we multiply Math.E to get 10?

Math.log(10);    // returns 2.302585092994046