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 of x.
  • Math.asinh(x) Returns the inverse hyperbolic sine of x.
  • Math.atanh(x) Returns the inverse hyperbolic tangent of x
  • Math.cbrt(x) Returns the cubed root of x.
  • Math.clz32(x) Returns the number of leading zero bits in the 32-bit integer representation of x.
  • Math.cosh(x) Returns the hyperbolic cosine of x.
  • Math.expm1(x) Returns the result of subtracting 1 from the exponential function of x
  • Math.fround(x) Returns the nearest single-precision float of x.
  • 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 of 1 + x.
  • Math.log10(x) Returns the base 10 logarithm of x.
  • Math.log2(x) Returns the base 2 logarithm of x.
  • Math.sign(x) Returns -1 if the x is negative, 0 if x is +0 or -0, or 1 if x is positive.
  • Math.sinh(x) Returns the hyperbolic sine of x.
  • Math.tanh(x) Returns the hyperbolic tangent of x.
  • 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.