2 min read

Math Object

The Math object allows you to perform mathematical tasks on numbers. Unlike other global objects, Math is not a constructor. All properties and methods of Math are static.

1. Constants (Properties)

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

console.log(Math.PI); // 3.141592653589793
console.log(Math.E);  // 2.718281828459045 (Euler's number)
console.log(Math.SQRT2); // 1.4142135623730951 (Square root of 2)

2. Rounding Methods

There are four 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 (removes decimals).
Math.round(4.6); // 5
Math.round(4.4); // 4

Math.ceil(4.1);  // 5
Math.floor(4.9); // 4

Math.trunc(4.9); // 4
Math.trunc(-4.9); // -4 (Math.floor would return -5)

3. Arithmetic Methods

  • Math.pow(x, y): Returns the value of x to the power of y.
  • Math.sqrt(x): Returns the square root of x.
  • Math.abs(x): Returns the absolute (positive) value of x.
  • Math.sign(x): Returns -1, 0, or 1 depending on the sign.
Math.pow(8, 2); // 64
Math.sqrt(64);  // 8
Math.abs(-4.7); // 4.7

4. Min and Max

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

Math.min(0, 150, 30, 20, -8, -200); // -200
Math.max(0, 150, 30, 20, -8, -200); // 150

5. Random

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

Math.random(); // e.g., 0.123456789

programming/javascript/vanilla/javascript programming/javascript/vanilla/data-types