Math Constants and Functions in JavaScript
In this tutorial, we’ll learn about Math Object in JavaScript, which allows us to use mathematical constants such as π
, e
, √2
and perform mathematical operations on numbers such as pow()
, sqrt()
, max()
, min()
, random()
, abs()
, ceil()
, floor()
, round()
, and truc()
.
Math Constants
Math Object in JavaScript provides 8 mathematical constants that can be used:
Math.E // returns 2.718281828459045 (Euler's number)
Math.PI // returns 3.141592653589793 (PI)
Math.SQRT2 // returns 1.4142135623730951 (square root of 2)
Math.SQRT1_2 // returns 0.7071067811865476 (square root of 1/2)
Math.LN2 // returns 0.6931471805599453 (natural logarithm of 2)
Math.LN10 // returns 2.302585092994046 (natural logarithm of 10
Math.LOG2E // returns 1.4426950408889634 (base 2 logarithm of E)
Math.LOG10E // returns 0.4342944819032518 (base 10 logarithm of E)
Calculate circumference of a circle
Let’s use Math.PI
constant to calculate the circumference 2πr
of a circle given the radius r
:
function calculateCircumference(radius) {
return 2 * Math.PI * radius;
}
calculateCircumference(10); // returns 62.83185307179586
Math Pow
The Math.pow(a, b)
function returns the a (base) to the power of b (exponent), i.e. ab.
Math.pow(4, 3);
// returns 64 i.e. 4×4×4
Math.pow(-4, 3);
// returns -64 i.e. (-4)×(-4)×(-4)
Math.pow(4, -3);
// returns 0.015625 i.e. 1 ÷ (4 × 4 x 4)
Math.pow(64, 0.5);
// returns 8 i.e. 2√64
Math.pow(-64, 0.5);
// returns NaN i.e. 2√-64 square root number cannot be negative
Math.pow(64, -0.5);
// returns 0.125 i.e. 1 ÷ 2√64 = 1/8
Let’s breakdown the result of above examples for clear understanding:
Math.pow(a, b) | ab | breakdown | result |
---|---|---|---|
Math.pow(4, 3) | 43 | 4 × 4 x 4 | 64 |
Math.pow(-4, 3) | (-4)3 | (-4) × (-4) x (-4) | -64 |
Math.pow(4, -3) | 4(-3) | 1 ÷ (4 × 4 x 4) | 0.015625 |
Math.pow(64, 0.5) | 640.5 | 2√64 | 8 |
Math.pow(-64, 0.5) | (-64)0.5 | 2√-64 | NaN |
Math.pow(64, -0.5) | 64(-0.5) | 1 ÷ 2√64 | 0.125 |
Exponentiation Operator (**)
It is very interesting to know that JavaScript ES6 provide shorthand syntax **
for Math power also known as exponentiation operator. So the above Math.pow
examples are same as:
console.log(4 ** 3); // returns 64
console.log((-4) ** 3); // returns -64
console.log(4 ** -3); // returns 0.015625
console.log(64 ** 0.5); // returns 8
console.log((-64) ** 0.5); // returns NaN
console.log(64 ** -0.5); // returns 0.125
Please note that if you are using shorthand syntax with -ve base then you must wrap the base in parenthesis ()
to avoid SyntaxError.
➤ -4 ** 3
Uncaught SyntaxError: Unary operator used immediately before exponentiation expression. Parenthesis must be used to disambiguate operator precedence
➤ (-4) ** 3
-64
Create square and cube methods using exponentiation operator
Let’s create some math power methods using exponentiation operator **
:
const square = x => x ** 2;
const cube = x => x ** 3;
square(4); // returns 16
cube(3); // returns 27
Math Sqrt
The Math.sqrt(x)
function returns the square root of the given number.
Math.sqrt(0); // returns 0
Math.sqrt(null); // returns 0
Math.sqrt(25); // returns 5
Math.sqrt(1); // returns 1
Math.sqrt(0.5); // returns 0.7071067811865476
Math.sqrt(-5); // returns NaN as number cannot be negative
Math.sqrt(NaN); // returns NaN as number cannot be NaN
Create our own squareroot method
Let’s create our own squareroot
methods using ES6 exponentiation operator **
:
const squareroot = x => x ** 0.5;
squareroot(0); // returns 0
squareroot(null); // returns 0
squareroot(25); // returns 5
squareroot(1); // returns 1
squareroot(0.5); // returns 0.707106781186547
squareroot(-5); // returns NaN as number cannot be negative
squareroot(NaN); // returns NaN as number cannot be NaN
Keep in mind that the square root of negative numbers doesn’t exist among the set of real numbers so JavaScript returns NaN
. Square root of negative numbers is an imaginary number which is represented by i
i.e. √-1 = i
Math Max
The Math.max(value1, value2, value3, ...)
function returns the largest value out of given values.
Math.max(1, 3, 2, 0, -1);
// returns 3
If any argument cannot be converted to a number, NaN
is returned.
Math.max(1, 3, 2, '0', -1);
// returns 3 as '0' is converted to numeric 0
Math.max(1, 3, 2, 'zero', -1);
// returns NaN as 'zero' cannot be converted to numeric value
Find the largest number from an array
Let’s use Math.max
function to find a largest number from an array in three ways:-
① Using spread operator ...
const numbers = [1, 2, 3, 4, 5];
Math.max(...numbers);
// returns 5
② Using function prototype apply()
method
const numbers = [1, 2, 3, 4, 5];
Math.max.apply(null, numbers);
// returns 5
③ Using Array.reduce()
method
const numbers = [1, 2, 3, 4, 5];
numbers.reduce((a,b) => Math.max(a,b));
// returns 5
However, both spread (...)
and apply()
will either fail or return the wrong result if the array has too many elements, because they try to pass the array elements as function parameters. The Array.reduce()
method does not have this problem.
Math Min
The Math.min(value1, value2, value3, ...)
function returns the smallest value out of given values.
Usage example of Math.min
is same as Math.max
function.
Math.min(1, 3, 2, 0, -1); // returns -1
Math.min(1, 3, 2, '0', -1); // returns -1
Math.min(1, 3, 2, 'zero', -1); // returns NaN
const numbers = [1, 2, 3, 4, 5];
Math.min(...numbers); // returns 1
Math.min.apply(null, numbers); // returns 1
numbers.reduce((a,b) => Math.min(a,b)); // returns 1
Math Random
The Math.random()
functions returns a floating point random number between 0 (inclusive) to 1 (exclusive)
0 ≤ Math.random() < 1
Let’s create some useful methods using Math.random()
function:
Generate a random integer given the max range
Let’s first create a method getRandomInt
, which returns a random integer given the max range
const getRandomInt = (max) => Math.floor(Math.random() * max) + 1;
Let’s use this method to find a random user name from the given array
const userList = ["Alice", "Bob", "Charlie", "David", "Eric", "Franklin", "Gavin", "Harry", "Iris",
"Joey", "Kate", "Leo", "Monica", "Nancy", "Oscar", "Phoebe", "Quinn", "Ross",
"Sofia", "Tyler", "Umar", "Victor", "Wilson", "Xena", "Yasmine", "Zara"];
const getRandomUser = () => userList[getRandomInt(userList.length)];
console.log(getRandomUser()); // Wilson
console.log(getRandomUser()); // Charlie
console.log(getRandomUser()); // Leo
console.log(getRandomUser()); // Joey
console.log(getRandomUser()); // Gavin
Generate a random integer between two values (inclusive)
Let’s first create a method getRandomIntInclusive
, which returns a random integer between two values (inclusive)
const getRandomIntInclusive = (min, max) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
};
Let’s use this method to generate an array of 10 elements with two-digits random numbers i.e. between 10 to 99
var numbers = [];
var min = 10;
var max = 99;
for ( var i = 0; i < 10; i++ ) {
numbers.push(getRandomIntInclusive(min, max));
}
console.log(numbers);
// [25, 55, 95, 51, 47, 10, 74, 86, 74, 77]
Shuffle the elements of an array
This is very interesting use of Math.random()
function with Array.sort()
functions to shuffle elements of an array. Let’s create our shuffleElements
method:
const shuffleElements = (list) => list.sort(() => Math.random() - 0.5);
The idea here is generate random number using Math.random()
between -0.5 to 0.5 and feed it to Array.sort()
function which sort an array based on returned value is +ve, or 0, or -ve
Let’s use this method:
const list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(shuffleElements(list));
// [6, 1, 2, 4, 3, 9, 5, 8, 7]
console.log(shuffleElements(list));
// [9, 6, 8, 1, 2, 7, 4, 5, 3]
console.log(shuffleElements(list));
// [6, 7, 3, 1, 2, 5, 8, 9, 4]
Math Abs
The Math.abs(x)
function returns the absolute of the a number i.e. |x|
Math.abs('-1'); // 1
Math.abs(-2); // 2
Math.abs(null); // 0
Math.abs(''); // 0
Math.abs([]); // 0
Math.abs([2]); // 2
Math.abs([1,2]); // NaN
Math.abs({}); // NaN
Math.abs('string'); // NaN
Math.abs(); // NaN
Find absolute difference between two numbers
Let’s use Math.abs()
to find the absolute difference between two given numbers:
const difference = (a, b) => Math.abs(a-b);
console.log(difference(3, 5)); // 2
console.log(difference(5, 3)); // 2
Math Ceil
The Math.ceil(x)
function is used to round off the given number towards ceiling means upward direction.
x ≤ Math.ceil(x) ≤ x+1
Math.ceil(0.95); // 1
Math.ceil(45.95); // 46
Math.ceil(45.05); // 46
Math.ceil(-0.95); // -0
Math.ceil(-45.05); // -45
Math.ceil(-45.95); // -45
Math.ceil(null); // 0
Math Floor
The Math.floor(x)
function is used to round off the given number towards floor means downward direction.
x-1 ≤ Math.floor(x) ≤ x
Math.floor(0.95); // 0
Math.floor(45.95); // 45
Math.floor(45.05); // 45
Math.floor(-0.95); // -1
Math.floor(-45.05); // -46
Math.floor(-45.95); // -46
Math.floor(null); // 0
Get a fraction part of a number
Let’s create a method fraction
to get a fraction part of the number using Math.floor()
and Math.abs()
functions:
const fraction = (x) => Math.abs(x) - Math.floor(Math.abs(x));
fraction(45.95); // 0.95
fraction(45.05); // 0.05
fraction(-45.95); // 0.95
fraction(-45.05); // 0.05
Get quotient and remainder of a division of two whole numbers
The Math.floor()
and %
can be used find quotient and remainder of a division of two whole numbers respectively:
var dividend = 14;
var divisor = 3;
console.log("quotient", Math.floor(dividend/divisor));
console.log("remainder", dividend % divisor);
// quotient 4
// remainder 2
Math Round
The Math.round(x)
function is used to round off the given number to the nearest integer in any direction, upward or downward.
console.log(Math.round(0.9));
// 1
console.log(Math.round(5.95), Math.round(5.5), Math.round(5.05));
// 6 6 5
console.log(Math.round(-5.05), Math.round(-5.5), Math.round(-5.95));
// -5 -5 -6
Math Trunc
The Math.trunc(x)
function returns the integer part of a number by removing decimal part.
Math.trunc(0.123); // 0
Math.trunc(12.34); // 12
Math.trunc(-0.123); // -0
Math.trunc(-12.34); // -12
Math.trunc('foo'); // NaN
Note that Math.trunc(x)
function do not apply any rounding logic and simply truncate the dot and decimal part of the number.
Create our own truncate method
Let’s create our own truncate
methods using Math.ceil()
and Math.floor()
functions:
const truncate = (x) => x < 0 ? Math.ceil(x) : Math.floor(x);
truncate(0.123); // 0
truncate(12.34); // 12
truncate(-0.123); // -0
truncate(-12.34); // -12
truncate('foo'); // NaN
Remaining Math Functions
We have covered most of the frequently used Math Object functions in JavaScript in details. These are the list of remaining Math functions which might be required in complex mathematical calculation.
Method | Description |
---|---|
acos(x) | Returns the arccosine of x, in radians |
acosh(x) | Returns the hyperbolic arccosine of x |
asin(x) | Returns the arcsine of x, in radians |
asinh(x) | Returns the hyperbolic arcsine of x |
atan(x) | Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians |
atan2(y, x) | Returns the arctangent of the quotient of its arguments |
atanh(x) | Returns the hyperbolic arctangent of x |
cbrt(x) | Returns the cubic root of x |
cos(x) | Returns the cosine of x (x is in radians) |
cosh(x) | Returns the hyperbolic cosine of x |
exp(x) | Returns the value of ex, where e is Euler’s number |
expm1(x) | Returns the value of (ex-1), where e is Euler’s number |
log(x) | Returns the natural logarithm (base e) of x |
sin(x) | Returns the sine of x (x is in radians) |
sinh(x) | Returns the hyperbolic sine of x |
tan(x) | Returns the tangent of an angle |
tanh(x) | Returns the hyperbolic tangent of a number |