JavaScript Math Object
Subject: JavaScript
The Math object in JavaScript is a built-in object that provides a wide range of mathematical constants and functions. Unlike other objects, Math is not a constructor, so you don’t create an instance of it—just use Math. followed by the method or property.
Why Use the Math Object?
- Perform tasks like rounding, powers, square roots, random numbers, and more.
- Access useful constants like PI, E, and logarithmic values.
Accessing the Math Object
Math methods work directly on numbers and return results immediately.
Commonly Used Math Methods
- Math.round(x) Rounds a number to the nearest integer.
- Math.ceil(x) Rounds upward to the nearest integer.
- Math.floor(x) Rounds downward to the nearest integer.
- Math.trunc(x) Removes the decimal part of a number.
- Math.pow(base, exponent) Returns the base raised to the power of the exponent.
- Math.sqrt(x) Returns the square root of a number.
- Math.abs(x) Returns the absolute value.
- Math.min() and Math.max() Return the smallest or largest number among the arguments.
- Math.random() Returns a random number between 0 (inclusive) and 1 (exclusive).
Generate a random integer between 1 and 10:
- Math.cbrt(x) Returns the cube root of a number.
Math Constants
Math provides constants like Math.PI, Math.E, Math.LN2, etc. for common mathematical values.
Example: Dice Roll Simulator
Key Takeaways
- The Math object provides methods for common and advanced math operations.
- It is not a constructor, so no instantiation is needed.
- Common methods include
round(),floor(),ceil(),sqrt(),pow(), andrandom(). - Combine
Math.random()withMath.floor()to generate random integers. - Constants like
Math.PIandMath.Eare frequently used in calculations.