Math
Math
is a built-in object with many useful methods that implement various mathematical functions. Here is a list of more frequently used ones for your reference.
Math.abs(x)
, Returns the absolute value of x.Math.sign(x)
, Returns the sign of the x, indicating whether x is positive, negative, or zero.Math.min
, Returns the smallest of its arguments.Math.max
, Returns the largest of its arguments.
Note:
min
andmax
take in any number of arguments.
Math.random()
, Returns a pseudo-random number between 0 and 1.Math.round(x)
, Returns the value of the number x rounded to the nearest integer.Math.trunc(x)
, Returns the integer portion of x, removing any fractional digits.Math.floor(x)
, Returns the largest integer less than or equal to x.Math.ceil(x)
, Returns the smallest integer greater than or equal to x.Math.fround(x)
, Returns the nearest single precision float representation of x.
Caution: be careful with the negative arguments to functions like
ceil
andfloor
.
console.log(Math.ceil(7.004)); console.log(Math.ceil(-7.004)); console.log(Math.floor(5.05)); console.log(Math.floor(-5.05));
Math.pow(x, y)
, Returns base x to the exponent power y.Math.exp(x)
, Returns Ex, where x is the argument, and E is Euler's constant (2.718..., the base of the natural logarithm).Math.log(x)
, Returns the natural logarithm of x.Math.log2(x)
, Returns the base-2 logarithm of x.Math.log10(x)
, Returns the base-10 logarithm of x.Math.sqrt(x)
, Returns the positive square root of x.
There are many useful constants built into Math
object as well:
console.log(Math.E); console.log(Math.PI); console.log(Math.SQRT2); console.log(Math.SQRT1_2); console.log(Math.LN10); console.log(Math.LOG2E); console.log(Math.LOG10E);
The Math
object includes many other static methods and properties. Please consult the MDN Reference page on Standard built-in Objects -> Math
Caution:
- Many
Math
functions have a precision that's implementation-dependent.Math
functions do not work withBigInt
.