## Useful JavaScript Math Functions and How to Use Them

The built-in JavaScript Math object includes a number of useful functions for performing a variety of mathematical operations. Let’s take a look and see how they work and what you can use them for.

## Math.max and Math.min

These functions do pretty much what you’d expect: they return the maximum or minimum of a list of the provided arguments:

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

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

Logic All have to be `Number` data type. Otherwise, `NaN` will be returned:

``````Math.max('a','b','c')
<< NaN

Math.min(5,"hello",6)
<< NaN
``````

Be careful though. javascript will try to force Values ​​in a Number:

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

In this example, the boolean value `true` numbers are constrained `1`, which is why it is returned as the minimum value. If you’re not familiar with type coercion, it occurs when the operands of an operator are of different types. In this case, JavaScript will attempt to convert one operand to an equivalent value of the type of the other operand. You can read more about type coercion JavaScript: Novice to Ninja, 2nd EditionIn Chapter 2.

A list of numbers needs to be provided as an argument, not an array, but you can use the spread operator (`...`) to unpack an array of numbers:

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

`Math.max` The function is useful for finding the high score from a list 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
``````

`Math.min` The function is useful for finding the best 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

One absolute value There is only the size of the number, whatever its size. This means that positive numbers remain the same and negative numbers lose their minus sign. `Math.abs` The function will calculate the absolute value of its argument:

``````Math.abs(5)
<< 5

Math.abs(-42)
<< 42

Math.abs(-3.14159)
<< 3.14159
``````

Why would you want to do this? ok sometimes you want to calculate gap Between two values, you get the smallest by subtracting the largest from it, but often you won’t know which is the smaller of the two values ​​beforehand. To get around this, you can subtract the numbers in any order and take the absolute values:

``````const x = 5
const y = 8

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

A practical example might be on a money saving website, where you want to know how much you can save by calculating the difference between two deals, as you will be dealing with live price data and will not know in advance how much you can save. Which deal was the cheapest:

``````const dealA = 150
const dealB = 167

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

## math.pow

`Math.pow` Performs power calculations, such as:

``````3⁴ = 81
``````

In the above example, 3 is known as Base is number and 4 exponent, We would read this as “3 to the power of 4 is 81”.

The function accepts two values ​​— the base and the exponent — and returns the result of raising the base to the power of the exponent:

``````Math.pow(2,3)
<< 8

Math.pow(8,0)
<< 1

Math.pow(-1,-1)
<< -1
``````

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

``````2 ** 3
<< 8

8 ** 0
<< 1

(-1) ** (-1)
<< -1
``````

## calculation of roots

Roots are the opposite operation of powers. For example, since the square of 3 is 9, the square root of 9 is 3.

`Math.sqrt` Can be used to return the square root of a 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-numeric value is supplied as an argument:

``````Math.sqrt(-1)
<< NaN

Math.sqrt("four")
<< NaN
``````

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

``````Math.sqrt('4')
<< 2

Math.sqrt(true)
<< 1
``````

`Math.cbrt` Returns the cube root of a number. It accepts all numbers — including negative numbers. It will also try to coerce the type if a value is used that is not a number. If it can’t coerce the value to a number, it will return `NaN`,

``````Math.cbrt(1000)
<< 10

Math.cbrt(-1000)
<< -10

Math.cbrt("10")
<< 2.154434690031884

Math.cbrt(false)
<< 0
``````

It is possible to calculate other roots using exponentiation operators and fractional powers. For example, the fourth root of a number can be found by raising it to one-fourth power (or 0.25). So the following code will return the fourth root of 625:

``````625 ** 0.25
<< 5
``````

To find the fifth root of a number, you raise it to the power of one fifth (or 0.2):

``````32 ** 0.2
<< 2
``````

In general, to find the nth root of a number, you raise it to its power. `1/n`So to find the sixth root of one million, you raise it to the power of 1/6:

``````1000000 ** (1/6)
<< 9.999999999999998
``````

Note that there is a rounding error here, since the answer must be exactly 10. This is often the case with fractional powers that cannot be expressed exactly in binary. (You can read more about this rounding issue in “A Guide to Rounding Numbers in JavaScript”.)

Also note that you cannot find the roots of negative numbers if the root is even. it will come back `NaN`, So you can’t try to find the 10th root of -7, for example (because 10 is even):

``````(-7) ** 0.1
<< NaN
``````

One reason to calculate the roots may be to calculate the rate of growth. For example, let’s say you want to multiply your profit by 10 times by the end of the year. How much does your profit need to grow every month? To figure it out, you need to calculate the 12th root of 10, or the twelfth power of 10:

``````10 ** (1/12)
<< 1.2115276586285884
``````

This result tells us that the monthly growth factor for 10x profits by the end of the year should be approximately 1.21. Or to put it another way, you would need to increase your profit by 21% every month to reach your goal.

## log and exponent

logarithm – or log for short – can be used to find the exponent of the calculation. For example, imagine you want to solve the following equation:

``````2ˣ = 100
``````

In the above equation, `x` Definitely not an integer, since 100 is not a power of 2. This can be solved using base 2 logarithms:

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

`Math` object has one `log2` Method that will do this calculation:

``````Math.log2(100)
<< 6.643856189774724
``````

there is also a `log10` Method that does the same calculation, but uses 10 as the base number:

``````Math.log10(100)
<< 2
``````

This result is telling us that, to get 100, you need to raise 2 to the power of 10.

There is another log method, which is justified `Math.log`, it calculates Naturalwhich uses euler’s number , `e` (about 2.7) — as a base. This may seem an odd value to use, but it actually occurs quite often in nature when exponential growth occurs – hence the name “natural logarithm”:

``````Math.log(10)
<< 4.605170185988092

Math.log(Math.E)
<< 1
``````

The final calculation shows that Euler’s number (`e`) — which is stored as a constant `Math.E` – needs to be raised to a power of 1 to get itself. This makes sense, because any number to the power of 1 is exactly the same. Same result can be obtained if 2 and 10 are provided as arguments `Math.log2` And `Math.log10`,

``````Math.log2(2)
<< 1

Math.log10(10)
<< 1
``````

Why would you use logarithms? With fast-growing data it is common to use a logarithmic scale so that the rate of growth is easier to see. The logarithmic scale was often used to measure the number of daily COVID-19 cases during the pandemic because they were rising so quickly.

If you are lucky enough to have a website that is growing rapidly in popularity (eg, doubling every day) you can use a logarithmic scale before displaying a graph to show how your popularity is growing. may consider using.

## Ear

you may miss studying pythagoras theorem In school. It states that the length of the longest side (the Ear) can be found using the following formula:

``````h² = x² + y²
``````

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

`Math` object has one `hypot` method that will calculate the length of the hypotenuse when the other two lengths are provided as arguments. For example, if one side is 3 and the other is 4, we can calculate the hypotenuse using the following code:

``````Math.hypot(3,4)
<< 5
``````

But why would it ever be useful? Well, the hypotenuse is the measure of the shortest distance between two points. This means that, if you know the x and y coordinates of two elements on the page, you can use this function to calculate how far apart they are:

``````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 this short roundup has been useful and helps you harness the full power of JavaScript Math Objects in your projects.