JavaScript for impatient programmers (beta)
Please support this book: buy it or donate
(Ad, please don’t block.)

15. Math

Math is an object with data properties and methods for processing numbers.

You can see it as a poor man’s module. Today, it would probably be created as a module, but it has existed since long before modules.

15.1. Data properties

15.2. Exponents, roots, logarithms

15.3. Rounding

Rounding means converting an arbitrary number to an integer (a number without a decimal fraction). Tbl. 13 lists the available functions and what they return for a few representative inputs.

Table 13: Rounding functions of Math.
-2.9 -2.5 -2.1 2.1 2.5 2.9
Math.floor -3 -3 -3 2 2 2
Math.ceil -2 -2 -2 3 3 3
Math.round -3 -2 -2 2 3 3
Math.trunc -2 -2 -2 2 2 2

15.4. Trigonometric Functions

All angles are specified in radians. Use the following two functions to convert between degrees and radians.

function toRadians(degrees) {
  return degrees / 180 * Math.PI;
}
function toDegrees(radians) {
  return radians / Math.PI * 180;
}

15.5. asm.js helpers

WebAssembly is a virtual machine based on JavaScript that is supported by most JavaScript engines.

asm.js is a precursor to WebAssembly. It is a subset of JavaScript that produces fast executables if static languages (such as C++) are compiled to it. In a way, it is also a virtual machine, within the confines of JavaScript.

The following two methods help asm.js and have few use cases, otherwise.

15.6. Various other functions

15.7. Sources