Common math operations in JavaScript

Sunday, Aug 16, 2020

JavaScript has built-in Math and Number objects. Some commonly used methods and properties are:

Check if number is legit

Zero divided by zero gives a special value, NaN. Any other number divided by zero gives +/- Infinity. While isNaN() checks if the number is NaN, isFinite() checks if a number is anything but NaN, +Infinity or -Infinity.

console.log(Number.isNaN(0), Number.isNaN(3/0), Number.isNaN(0/0));
// false false true

console.log(Number.isFinite(3), Number.isFinite(1/0), Number.isFinite(0/0));
//true false false

Random numbers, exponentiation, rounding and constants

Pseudo random numbers in range [0, 1) can be generated using Math.random(), ** operator for exponentiation, Math.floor(), Math.ceil(), Math.round() and Math.trunc() for ways to round off the floating number. Math.PI and Math.E properties hold the usual constants:

console.log(Math.random(), Math.PI, Math.E);
//0.004338876794353297 3.141592653589793 2.718281828459045

console.log(2 ** 3);

const r = 10 * Math.random();
console.log(r, Math.floor(r), Math.ceil(r), Math.round(r), Math.trunc(r));
//9.928281608108966 9 10 10 9


Math.log(), Math.log10() and Math.log2() for natural log and log to the base 10 and 2 respectively:

console.log(Math.log(r), Math.log10(r), Math.log2(r));
//2.2953874125392044 0.9968740870959596 3.3115440369892597

Sign and absolute value functions

Math.sign() will return -1, 0 or 1 for -ve, 0 and +ve numbers respectively.

console.log(Math.abs(r * -1), Math.sign(r))
//9.928281608108966 1

Max, min and square root of sum of squares

These functions generally would use multiple arguments. If the numbers are in an array, (...arrayName) notation can be used:

const a = [1, 2, 3];
console.log(Math.max(...a), Math.min(...a), Math.hypot(...a));
//3 1 3.741657386773941