The Math Object

The Math object in JavaScript provides properties and methods for mathematical constants and functions. It is a built-in object and is not a constructor, so you do not create instances of it.

Illustration of the_math_object
Illustration of the_math_object

💡 Key Feature

All methods and properties of Math are static, so you call them directly on Math without instantiating it.

Commonly Used Properties

Math Properties
PropertyDescription
Math.PIRatio of the circumference of a circle to its diameter (~3.14159)
Math.EEuler's number, base of natural logarithms (~2.718)
Math.SQRT2Square root of 2 (~1.414)
Math.LN10Natural logarithm of 10 (~2.302)

Essential Math Methods

  • Math.abs(x) - Returns the absolute value of x.
  • Math.round(x) - Rounds x to the nearest integer.
  • Math.floor(x) - Rounds x down to the nearest integer.
  • Math.ceil(x) - Rounds x up to the nearest integer.
  • Math.max(...values) - Returns the largest of the given numbers.
  • Math.min(...values) - Returns the smallest of the given numbers.
  • Math.random() - Returns a pseudo-random number between 0 (inclusive) and 1 (exclusive).
  • Math.sqrt(x) - Returns the square root of x.
  • Math.pow(base, exponent) - Returns base raised to the power of exponent.

💡 Using Math.random()

To generate a random integer between two values min and max (inclusive):

📌 Deep Dive: Random Integer Between min and max

JAVASCRIPT
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
Example usage
getRandomInt(1, 10); // Returns an integer between 1 and 10

Method Behavior Comparison

Rounding Methods
MethodInputOutput
Math.floor(4.9)4.94
Math.ceil(4.1)4.15
Math.round(4.5)4.55
Math.round(4.4)4.44

⚠️ Important

Since Math.random() returns a floating-point number in [0, 1), using Math.floor with multiplication is necessary to convert it into an integer range.

Additional Useful Methods

  • Math.trunc(x) - Removes the decimal part of x, effectively truncating toward zero.
  • Math.sign(x) - Returns 1 if positive, -1 if negative, and 0 if zero.
  • Math.log(x) - Natural logarithm (base e) of x.
  • Math.exp(x) - Returns e raised to the power of x.

💡 Remember

All Math methods are deterministic except Math.random(), which generates pseudo-random values.