New Math Methods
The new emphasis on gaming and graphics that led ECMAScript 6 to include typed arrays in JavaScript also led to the realization that a JavaScript engine could do many mathematical calculations more efficiently. But optimization strategies like asm.js, which works on a subset of JavaScript to improve performance, need more information to perform calculations in the fastest way possible. For instance, knowing whether the numbers should be treated as 32-bit integers or as 64-bit floats is important for hardware-based operations, which are much faster than software-based operations.
As a result, ECMAScript 6 added several methods to the Math
object to improve the speed of common mathematical calculations. Improving the speed of common calculations also improves the overall speed of applications that perform many calculations, such as graphics programs. The new methods are listed below:
Math.acosh(x)
Returns the inverse hyperbolic cosine ofx
.Math.asinh(x)
Returns the inverse hyperbolic sine ofx
.Math.atanh(x)
Returns the inverse hyperbolic tangent ofx
Math.cbrt(x)
Returns the cubed root ofx
.Math.clz32(x)
Returns the number of leading zero bits in the 32-bit integer representation ofx
.Math.cosh(x)
Returns the hyperbolic cosine ofx
.Math.expm1(x)
Returns the result of subtracting 1 from the exponential function ofx
Math.fround(x)
Returns the nearest single-precision float ofx
.Math.hypot(...values)
Returns the square root of the sum of the squares of each argument.Math.imul(x, y)
Returns the result of performing true 32-bit multiplication of the two arguments.Math.log1p(x)
Returns the natural logarithm of1 + x
.Math.log10(x)
Returns the base 10 logarithm ofx
.Math.log2(x)
Returns the base 2 logarithm ofx
.Math.sign(x)
Returns -1 if thex
is negative, 0 ifx
is +0 or -0, or 1 ifx
is positive.Math.sinh(x)
Returns the hyperbolic sine ofx
.Math.tanh(x)
Returns the hyperbolic tangent ofx
.Math.trunc(x)
Removes fraction digits from a float and returns an integer.
It’s beyond the scope of this book to explain each new method and what it does in detail. But if your application needs to do a reasonably common calculation, be sure to check the new Math
methods before implementing it yourself.