The Math Object
Math provides constants and functions for calculations.
Syntax
Math.round(x)
Math.max(a, b, c)The built-in Math object has methods and constants for mathematical tasks.
Math.round(),Math.floor(),Math.ceil()— rounding.Math.max(),Math.min()— largest / smallest.Math.abs(),Math.sqrt(),Math.pow().Math.PI— the constant π.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Cap a sidebar width to a maximum value using Math.min when the browser window is resized.
- Round up a pagination page count using Math.ceil so partial pages are not lost.
- Calculate the hypotenuse of a right triangle using Math.sqrt and Math.pow in a geometry tool.
More examples
Math.min and Math.max
Uses Math.min to ensure a sidebar width does not exceed a maximum even on narrow screens.
const windowWidth = 320;
const sidebarWidth = Math.min(windowWidth * 0.3, 250);
console.log(sidebarWidth); // 96 – capped at 250Math.ceil for page count
Uses Math.ceil to round up the page count so the last partial page is included.
const total = 53;
const pageSize = 10;
const pages = Math.ceil(total / pageSize);
console.log(pages); // 6Math.sqrt and Math.pow
Applies the Pythagorean theorem using Math.sqrt and Math.pow to compute a hypotenuse.
function hypotenuse(a, b) {
return Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
}
console.log(hypotenuse(3, 4)); // 5
Discussion