JavaScript’s Math is a built-in global object that provides mathematical constants and helper methods.
It is not a constructor, so you do not create it with new Math().
All methods are used in the form Math.xxx().
Common constants include:
Math.PIMath.EMath.LN2Math.SQRT2console.log(Math.PI); // 3.141592653589793Math.floor(4.9); // 4Math.ceil(4.1); // 5Math.round(4.5); // 5Math.trunc(4.9); // 4Math.max(1, 5, 3); // 5Math.min(1, 5, 3); // 1You can also combine them with spread syntax:
const nums = [4, 2, 9, 7];Math.max(...nums); // 9Math.abs(-10); // 10Math.pow(2, 3); // 8Math.sqrt(16); // 4Math.cbrt(27); // 3Many modern codebases prefer ** over Math.pow:
2 ** 3; // 8Math.random(); // 0 <= n < 1Random integer in a range:
function randomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min;}Math.sin(Math.PI / 2); // 1Math.cos(0); // 1Math.tan(0); // 0Remember that JavaScript trig functions use radians, not degrees.
Math is a lightweight but essential utility object.
The most commonly used parts in everyday development are: