 # Useful JavaScript Math Functions and Methods to Use Them

Nov 23, 2022

The built-in JavaScript Math object includes plenty of useful functions for performing quite a lot of mathematical operations. Let’s dive in and try how they work and what you would possibly use them for.

## Math.max and Math.min

These functions just about do what you’d expect: they return the utmost or minimum of the list of arguments supplied:

Math.max(1,2,3,4,5)
<< 5

Math.min(4,71,7,2,1,0)
<< 7

The arguments all should be of the Number data type. Otherwise, NaN shall be returned:

Math.max(‘a’,‘b’,‘c’)
<< NaN

Math.min(5,“hello”,6)
<< NaN

Be careful, though. JavaScript will try to coerce values right into a number:

Math.min(5,true,6)
<< 1

In this instance, the Boolean value true is coerced into the #1, which is why that is returned because the minimum value. Should you’re not accustomed to type coercion, it happens when the operands of an operator are of differing types. On this case, JavaScript will try to convert one operand to an equivalent value of the opposite operand’s type. You possibly can read more about type coercion in JavaScript: Novice to Ninja, 2nd Edition, in Chapter 2.

A listing of numbers must be supplied because the argument, not an array, but you should utilize the spread operator (…) to unpack an array of numbers:

Math.max([8,4,2,1])
<< 8

The Math.max function is helpful for locating the high rating from an inventory of scores saved in an array:

const scores = [23,12,52,6,25,38,19,37,76,54,24]
const highScore = Math.max(scores)
<< 76

The Math.min function is helpful for locating the most effective price on a price-comparison website:

const prices = [19.99, 20.25, 18.57, 19,75, 25, 22.50]
const bestPrice = Math.min(prices)
<< 18.57

## Absolute Values

An absolute value is just the dimensions of the number, regardless of what its size. Because of this positive numbers stay the identical and negative numbers lose their minus sign. The Math.abs function will calculate absolutely the value of its argument:

Math.abs(5)
<< 5

Math.abs(42)
<< 42

Math.abs(3.14159)
<< 3.14159

Why would you desire to do that? Well, sometimes you desire to calculate the difference between two values, which you’re employed out by subtracting the smallest from the most important, but often you won’t know which is the smallest of the 2 values upfront. To get around, this you’ll be able to just subtract the numbers in any order and take absolutely the value:

const x = 5
const y = 8

const difference = Math.abs(x y)
<< 3

A practical example is likely to be on a money-saving website, where you desire to understand how much you would save by calculating the difference between two deals, because you’d be coping with live price data and wouldn’t know upfront which deal was the most cost effective:

const dealA = 150
const dealB = 167

const saving = Math.abs(dealA dealB)
<< 17

## Math.pow

Math.pow performs power calculations, like these:

3= 81

In the instance above, 3 is generally known as the base number and 4 is the exponent. We’d read it as “3 to the facility of 4 is 81”.

The function accepts two values — the bottom and the exponent — and returns the results of raising the bottom to the facility of the exponent:

Math.pow(2,3)
<< 8

Math.pow(8,0)
<< 1

Math.pow(1,1)
<< 1

Math.pow has just about been replaced by the infix exponentiation operator (**) — introduced in ES2016 — which does the exact same operation:

2 ** 3
<< 8

8 ** 0
<< 1

(1) ** (1)
<< 1

## Calculating Roots

Roots are the inverse operation to powers. For instance, since 3 squared is 9, the square root of 9 is 3.

Math.sqrt could be used to return the square root of the number provided as an argument:

Math.sqrt(4)
<< 2

Math.sqrt(100)
<< 10

Math.sqrt(2)
<< 1.4142135623730951

This function will return NaN if a negative number or non-numerical value is provided as an argument:

Math.sqrt(1)
<< NaN

Math.sqrt(“4”)
<< NaN

But be careful, because JavaScript will try to coerce the sort:

Math.sqrt(‘4’)
<< 2

Math.sqrt(true)
<< 1

Math.cbrt returns the cube root of a number. This accepts all numbers — including negative numbers. It should also try to coerce the sort if a worth that’s not a number is used. If it could actually’t coerce the worth to a number, it can return NaN:

Math.cbrt(1000)
<< 10

Math.cbrt(1000)
<< 10

Math.cbrt(“10”)
<< 2.154434690031884

Math.cbrt(false)
<< 0

It’s possible to calculate other roots using the exponentiation operator and a fractional power. For instance, the fourth root of a number could be found by raising it to the facility one-quarter (or 0.25). So the next code will return the fourth root of 625:

625 ** 0.25
<< 5

To seek out the fifth root of a number, you’ll raise it to the facility of 1 fifth (or 0.2):

32 ** 0.2
<< 2

Generally, to search out the nth root of a number you’ll raise it to the facility of 1/n, so to search out the sixth root of one million, you’ll raise it to the facility of 1/6:

1000000 ** (1/6)
<< 9.999999999999998

Notice that there’s a rounding error here, as the reply ought to be exactly 10. This can often occur with fractional powers that may’t be expressed exactly in binary. (You possibly can read more about this rounding issue in “A Guide to Rounding Numbers in JavaScript“.)

Also note which you can’t find the roots of negative numbers if the basis is even. This can return NaN. So you’ll be able to’t attempt to search out the tenth root of -7, for instance (because 10 is even):

(7) ** 0.1
<< NaN

One reason it is advisable to calculate roots is to work out growth rates. For instance, say you desire to 10x your profits by the top of the yr. How much do your profits have to grow every month? To seek out this out, you’d have to calculate the twelfth root of 10, or 10 to the facility of a twelfth:

10 ** (1/12)
<< 1.2115276586285884

This result tells us that the monthly growth factor must be around 1.21 as a way to 10x profits by the top of the yr. Or to place it one other way, you’d need to extend your profits by 21% every month as a way to achieve your goal.

## Logs and Exponentials

Logarithms — or logs for brief — could be used to search out the exponent of a calculation. For instance, imagine you wanted to unravel the next equation:

2ˣ = 100

Within the equation above, x actually isn’t an integer, because 100 isn’t an influence of two. This could be solved through the use of base 2 logarithms:

x = log²(100) = 6.64 (rounded to 2 d.p.)

The Math object has a log2 method that can perform this calculation:

Math.log2(100)
<< 6.643856189774724

It also has a log10 method that performs the identical calculations, but uses 10 as the bottom number:

Math.log10(100)
<< 2

This result’s telling us that, to get 100, it is advisable raise 10 to the facility of two.

There’s one other log method, which is just Math.log. This calculates the natural logarithm, which uses Euler’s number — e (roughly 2.7) — as the bottom. This may appear to be a wierd value to make use of, however it actually occurs often in nature when exponential growth happens — hence the name “natural logarithms”:

Math.log(10)
<< 4.605170185988092

Math.log(Math.E)
<< 1

The last calculation shows that Euler’s number (e) — which is stored because the constant Math.E — must be raised to the facility of 1 to acquire itself. This is sensible, because any number to the facility of 1 is in actual fact itself. The identical results could be obtained if 2 and 10 are provided as arguments to Math.log2 and Math.log10:

Math.log2(2)
<< 1

Math.log10(10)
<< 1

Why would you utilize logarithms? It’s common when coping with data that grows exponentially to make use of a logarithmic scale in order that the expansion rate is less complicated to see. Logarithmic scales were often used to measure the variety of every day COVID-19 cases throughout the pandemic as they were rising so quickly.

Should you’re lucky enough to have a web site that’s growing rapidly in popularity (say, doubling every single day) you then might want to contemplate using a logarithmic scale before displaying a graph to indicate how your popularity is growing.

## Hypotenuse

You would possibly remember studying Pythagoras’ theorem in school. This states that the length of the longest side of a right-angled triangle (the hypotenuse) could be found using the next formula:

= x² + y²

Here, x and y are the lengths of the opposite two sides.

The Math object has a hypot method that can calculate the length of the hypotenuse when supplied with the opposite two lengths as arguments. For instance, if one side is length 3 and the opposite is length 4, we will work out the hypotenuse using the next code:

Math.hypot(3,4)
<< 5

But why would this ever be useful? Well, the hypotenuse is a measure of the shortest distance between two points. Because of this, if you happen to know the x and y coordinates of two elements on the page, you would use this function to calculate how far apart they’re:

const ship = {x: 220, y: 100}
const boat = {x: 340, y: 50}

const distance = Math.hypot(ship.x boat.x,ship.y boat.y)

I hope that this short roundup has been useful and helps you utilize the total power of the JavaScript Math object in your projects.