Loading lessons...
Math Object
The built-in Math object gives you math constants and functions.
Math constants
js
### Math.PI; // 3.141592653589793
### Math.E; // 2.718281828459045
Rounding methods
js
### Math.round(4.7); // 5 (rounds normally)
### Math.ceil(4.2); // 5 (always rounds up)
### Math.floor(4.7); // 4 (always rounds down)
### Math.trunc(4.9); // 4 (removes decimals)
Common functions
js
### Math.pow(2, 3); // 8
### Math.sqrt(16); // 4
### Math.abs(-5); // 5
### Math.max(1, 5, 3); // 5
### Math.min(1, 5, 3); // 1
Math.random
Math.random() returns a random number between 0 (included) and 1 (excluded):
js
Math.random(); // e.g. 0.523473...
Random integers
To get a random whole number between 1 and 10:
js
### Math.floor(Math.random() * 10) + 1;
TL;DR
- Math.PI and Math.E are constants.
- round, ceil, floor, and trunc round numbers.
- pow, sqrt, abs, max, min are common helpers.
- Math.random() returns 0 to just under 1.