JavaScript - Math

Selected Methods

Method Description
abs Returns the absolute value of a number. i.e. it returns the number if the number is positive and -1 × the number if the number is negative.
ceil Returns the smallest whole number greater than or equal to a number.
floor Returns the largest whole number less than or equal to a number.
max Returns the largest of its number arguments.
min Returns the smallest of its number arguments.
random Returns a random number between 0 and 1 which can be 0 but not 1.
round Returns the nearest whole number.

abs

The abs method returns the absolute value of a number. i.e. it returns the number if the number is positive and -1 × the number if the number is negative.

console.log(Math.abs(5)); // 5 console.log(Math.abs(-8)); // 8

ceil

The ceil method returns the smallest whole number greater than or equal to a number.

console.log(Math.ceil(5.2)); // 6 console.log(Math.ceil(24)); // 24 console.log(Math.ceil(-3.8)); // -3

floor

The floor method returns the largest whole number less than or equal to a number.

console.log(Math.floor(5.2)); // 5 console.log(Math.floor(24)); // 24 console.log(Math.floor(-3.8)); // -4

max

The max method returns the largest of its number arguments.

console.log(Math.max(3, 11, 7, 2)); // 11 console.log(Math.max(-8, 3)); // 3

min

The min method returns the smallest of its number arguments.

console.log(Math.min(3, 11, 7, 2)); // 2 console.log(Math.min(-8, 3)); // -8

random

The random method returns a random number between 0 and 1 which can be 0 but not 1.

console.log(Math.random()); // e.g. 0.6517522458452731

Multiply the random number to change the range of possible numbers.

console.log(10 * Math.random()); // 0 ≤ number < 10 console.log(42 * Math.random()); // 0 ≤ number < 42

Add to the random number to change the range of possible numbers.

console.log(10 + Math.random()); // 10 ≤ number < 11 console.log(10 + 42 * Math.random()); // 10 ≤ number < 52

Use Math.floor to generate whole numbers.

console.log(Math.floor(10 + 2 * Math.random())); // 10 ≤ number ≤ 11 console.log(Math.floor(10 + 42 * Math.random())); // 10 ≤ number ≤ 51

round

The round method returns the nearest whole number.

console.log(Math.round(3.2)); // 3 console.log(Math.round(3.5)); // 4 console.log(Math.round(3.9)); // 4

Further Help

You can find an excellent reference of properties and methods on the Mozilla Developer Network Math object page.