Math functions in JavaScript

Math is a global variable(namespace) for built in constants and functions that are very handy when developing. I will go through the most common ones in this article:

Starting with the most common constant, PI:

Math.PI // 3.141592653589793

To get the absolute difference between numbers without getting a negative number you can use the absolute function that is built in.

console.log(-23 - -22);// -> -1
console.log(Math.abs(-23 - -22));// -> 1

console.log(-23 + 22);// -> -1
console.log(Math.abs(-23 + 22));// -> 1

console.log(-23 - 22); // -45
console.log(Math.abs(-23 - 22)); // 45

Another useful Math function is max which takes a set of arguments and returns the biggest one:

console.log(Math.max(1,5,7,-90,222)); //->222 

min does the same but for smallest number:

console.log(Math.min(1,5,7,-90,222)); //->-90

to combine all these 3 functions we can find the absolute difference in range between a set of numbers:

console.log(Math.abs(Math.max(1,5,7,-90,222) - Math.min(1,5,7,-90,222))); //-> 312

Difference between -90 and 222 is 312 and that’s we got. If you are alert you might notice that in this case Math.abs was unnecessary and we would have got 312 regardless..

console.log(Math.max(1,5,7,-90,222) - Math.min(1,5,7,-90,222)); //-> 312

That’s true but what if we swap places with the Min and max?

console.log(Math.min(1,5,7,-90,222) - Math.max(1,5,7,-90,222)); //-> -312

Now you can see the power of Math.abs, if you don’t know for certain on which side of the – the numbers will fall. Math.abs can be very handy tool.

console.log(Math.abs(Math.min(1,5,7,-90,222) - Math.max(1,5,7,-90,222))); //-> 312

Another very common function is Math.random which returns a random number between 0 and 1.

console.log(Math.random()); //-> 0.2222222222

You’ll find a more useful way to use this function in this code snippet how to generate a random number with min and max value without any decimals:
Generate a random number

Some other math functions that can be handy:

Math.sqrt returns the Square root of a number:

console.log(Math.sqrt(100)); //-> 10

The Math.tan() function returns the tangent of a number:

console.log(Math.tan(100)); //-> -0.5872139151569291

The Math.log() function returns the natural logarithm of a number

console.log(Math.log(100)); // -> 4.605170185988092

You can find more of these at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math

Add your comment