Built-In Mathematical Calculations

Math is a built-in object with properties and methods for mathematical constants and functions. It is not a function object. Math works with the Number type. Math functions are all static, so each starts with Math.myfunctioncallhere(). Math.PI and Math.random() are two Math functions used a lot when doing calculations.

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.

In JavaScript, we can do this with the following:

trigonometry

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);