The Math
object in JavaScript provides a collection of methods and properties for performing mathematical operations. It is not a constructor, so all its methods and properties are static.
JavaScript Math Methods
Math.PI
,Math.sqrt()
,Math.pow()
are useful for mathematical constants and power calculations.Math.round()
,Math.ceil()
,Math.floor()
help in rounding numbers.Math.min()
,Math.max()
, andMath.random()
are useful for comparing numbers and generating random values.Math.log()
,Math.sin()
,Math.cos()
,Math.tan()
are essential for logarithmic and trigonometric calculations.
1. Math.PI
Represents the value of π (pi), approximately 3.14159.
console.log(Math.PI); // Output: 3.141592653589793
Usage: Used in calculations involving circles or angles.
2. Math.round()
Rounds a number to the nearest integer.
console.log(Math.round(4.7)); // Output: 5 console.log(Math.round(4.4)); // Output: 4
Usage: Useful for rounding off decimal numbers.
3. Math.ceil()
Rounds a number up to the next largest integer.
console.log(Math.ceil(4.1)); // Output: 5
Usage: Always rounds up, regardless of the decimal part.
4. Math.floor()
Rounds a number down to the next smallest integer.
console.log(Math.floor(4.9)); // Output: 4
Usage: Always rounds down, regardless of the decimal part.
5. Math.abs()
Returns the absolute value of a number.
console.log(Math.abs(-5)); // Output: 5
Usage: Converts negative numbers to positive.
6. Math.sqrt()
Returns the square root of a number.
console.log(Math.sqrt(16)); // Output: 4
Usage: Used to find the square root of a given number.
7. Math.pow()
Returns the base to the exponent power, that is, base^exponent
.
console.log(Math.pow(2, 3)); // Output: 8
Usage: Used to calculate powers of numbers.
8. Math.min()
Returns the smallest of zero or more numbers.
console.log(Math.min(0, 150, 30, 20, -8)); // Output: -8
Usage: Finds the minimum value from a set of numbers.
9. Math.max()
Returns the largest of zero or more numbers.
console.log(Math.max(0, 150, 30, 20, -8)); // Output: 150
Usage: Finds the maximum value from a set of numbers.
10. Math.random()
Returns a pseudo-random number between 0 (inclusive) and 1 (exclusive).
console.log(Math.random()); // Output: A random number between 0 and 1
Usage: Commonly used for generating random numbers.
11. Math.log()
Returns the natural logarithm (base e
) of a number.
console.log(Math.log(1)); // Output: 0
Usage: Used for logarithmic calculations.
12. Math.sin()
, Math.cos()
, Math.tan()
Returns the sine, cosine, or tangent of an angle (in radians).
console.log(Math.sin(Math.PI / 2)); // Output: 1 console.log(Math.cos(0)); // Output: 1 console.log(Math.tan(Math.PI / 4)); // Output: 1
Usage: Used in trigonometric calculations.
Summary
The Math
object provides a comprehensive set of functions for performing mathematical operations, making it an essential tool for developers working with numbers in JavaScript.