The Math
object in JavaScript provides a set of built-in mathematical functions and constants for performing mathematical operations. It’s not a constructor, so you don’t need to create an instance of it.
Mathematical Constants:
Math.PI
: Represents the ratio of the circumference of a circle to its diameter, approximately 3.14159.
console.log(Math.PI); // Outputs: 3.141592653589793
Basic Mathematical Functions:
Math.abs(x)
: Returns the absolute value of a number.Math.sqrt(x)
: Returns the square root of a number.Math.pow(x, y)
: Returns the base to the exponent power.Math.floor(x)
: Returns the largest integer less than or equal to a given number.Math.ceil(x)
: Returns the smallest integer greater than or equal to a given number.Math.round(x)
: Returns the value of a number rounded to the nearest integer.
console.log(Math.abs(-5));
// Outputs: 5
console.log(Math.sqrt(25));
// Outputs: 5
console.log(Math.pow(2, 3));
// Outputs: 8
console.log(Math.floor(3.9));
// Outputs: 3
console.log(Math.ceil(3.1));
// Outputs: 4
console.log(Math.round(4.6));
// Outputs: 5
Trigonometric Functions:
Math.sin(x)
: Returns the sine of a number.Math.cos(x)
: Returns the cosine of a number.Math.tan(x)
: Returns the tangent of a number.Math.atan2(y, x)
: Returns the arctangent of the quotient of its arguments.
console.log(Math.sin(Math.PI / 2));
// Outputs: 1
console.log(Math.cos(0));
// Outputs: 1
console.log(Math.tan(Math.PI / 4));
// Outputs: 1
console.log(Math.atan2(1, 1));
// Outputs: ~0.7853981633974483
Exponential and Logarithmic Functions:
Math.exp(x)
: Returnse
raised to the power of a number.Math.log(x)
: Returns the natural logarithm (basee
) of a number.Math.log(x)
: Returns the natural logarithm (basee
) of a number.
console.log(Math.exp(1));
// Outputs: ~2.718281828459045
console.log(Math.log(Math.E));
// Outputs: 1
console.log(Math.log10(100));
// Outputs: 2
Random Number Functions:
Math.random()
: Returns a pseudo-random number between 0 (inclusive) and 1 (exclusive).Math.floor(Math.random() * (max - min + 1)) + min
: Returns a random integer between the specified values.
console.log(Math.random());
// Outputs: A random number between 0 and 1
console.log(Math.floor(Math.random() * 10));
// Outputs: A random integer between 0 and 9
Other Functions:
Math.min(...args)
: Returns the smallest of zero or more numbers.Math.max(...args)
: Returns the largest of zero or more numbers.
console.log(Math.min(2, 5, 1));
// Outputs: 1
console.log(Math.max(2, 5, 1));
// Outputs: 5
Math Properties (Constants)
The syntax for any Math property is :
Math.property
.JavaScript provides 8 mathematical constants that can be accessed as Math properties:
Math.E
// returns Euler's number
Math.PI
// returns PI
Math.SQRT2
// returns the square root of 2
Math.SQRT1_2
// returns the square root of 1/2
// returns the natural logarithm of 2
Math.LN10
// returns the natural logarithm of 10
Math.LOG2E
// returns base 2 logarithm of E
Math.LOG10E
// returns base 10 logarithm of E