12.5. Math Methods

As with strings and arrays, JavaScript provides some built-in methods for the Math object. These allow us to perform calculations or tasks that are more involved than simple multiplication, division, addition, or subtraction.

12.5.1. Common Math Methods

The Math object contains over 30 methods. The table below provides a sample of the most frequently used options. More complete lists can be found here:

  1. W3 Schools Math Reference

  2. MDN Web Docs

To see detailed examples for a particular method, click on its name.

Ten Common Math Methods

Method

Syntax

Description

abs

Math.abs(number)

Returns the positive value of number.

ceil

Math.ceil(number)

Rounds the decimal number UP to the closest integer value.

floor

Math.floor(number)

Rounds the decimal number DOWN to the closest integer value.

max

Math.max(x,y,z,...)

Returns the largest value from a set of numbers.

min

Math.min(x,y,z,...)

Returns the smallest value from a set of numbers.

pow

Math.pow(x,y)

Returns the value of x raised to the power of y (x y).

random

Math.random()

Returns a random decimal value between 0 and 1, NOT including 1.

round

Math.round(number)

Returns number rounded to the nearest integer value.

sqrt

Math.sqrt(number)

Returns the square root of number.

trunc

Math.trunc(number)

Removes any decimals and returns the integer part of number.

12.5.2. Check Your Understanding

Follow the links in the table above for the floor, random, round, and trunc methods. Review the content and then answer the following questions.

Question

Which of the following returns -3 when applied to -3.87?

  1. Math.floor(-3.87)

  2. Math.random(-3.87)

  3. Math.round(-3.87)

  4. Math.trunc(-3.87)

Question

What is printed by the following program?

1
2
3
let num = Math.floor(Math.random()*10);

console.log(num);
  1. A random number between 0 and 9.

  2. A random number between 0 and 10.

  3. A random number between 1 and 9.

  4. A random number between 1 and 10.

Question

What is printed by the following program?

1
2
3
let num = Math.round(Math.random()*10);

console.log(num);
  1. A random number between 0 and 9.

  2. A random number between 0 and 10.

  3. A random number between 1 and 9.

  4. A random number between 1 and 10.