UNB/ CS/ David Bremner/ teaching/ cs2613/ books/ mdn/ Reference/ Global Objects/ Math

The Math namespace object contains static properties and methods for mathematical constants and functions.

Math works with the Number type. It doesn't work with BigInt.

Description

Unlike most global objects, Math is not a constructor. You cannot use it with the new operator or invoke the Atomics object as a function. All properties and methods of Math are static.

Note: Many Math functions have a precision that's implementation-dependent.

This means that different browsers can give a different result. Even the same JavaScript engine on a different OS or architecture can give different results!

Static properties

Static methods

Examples

Converting between degrees and radians

The trigonometric functions sin(), cos(), tan(), asin(), acos(), atan(), and atan2() expect (and return) angles in radians.

Since humans tend to think in degrees, and some functions (such as CSS transforms) can accept degrees, it is a good idea to keep functions handy that convert between the two:

function degToRad(degrees) {
  return degrees * (Math.PI / 180);
}

function radToDeg(rad) {
  return rad / (Math.PI / 180);
}

Calculating the height of an equilateral triangle

If we want to calculate the height of an equilateral triangle, and we know its side length is 100, we can use the formulae length of the adjacent multiplied by the tangent of the angle is equal to the opposite.

An equilateral triangle where a perpendicular of one edge is drawn from the opposite vertex, forming a right triangle with three sides marked as "adjacent", "opposite", and "hypotenuse". The angle between the "adjacent" and "hypotenuse" sides is 60 degrees.

In JavaScript, we can do this with the following:

50 * Math.tan(degToRad(60));

We use our degToRad() function to convert 60 degrees to radians, as Math.tan expects an input value in radians.

Returning a random integer between two bounds

This can be achieved with a combination of Math.random and Math.floor:

function random(min, max) {
  const num = Math.floor(Math.random() * (max - min + 1)) + min;
  return num;
}

random(1, 10);

Specifications

Browser compatibility

See also