The Math Object

Math provides constants and functions for calculations.

SyntaxMath.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

Try it yourself
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.

Example · js
const windowWidth = 320;
const sidebarWidth = Math.min(windowWidth * 0.3, 250);
console.log(sidebarWidth); // 96 – capped at 250

Math.ceil for page count

Uses Math.ceil to round up the page count so the last partial page is included.

Example · js
const total = 53;
const pageSize = 10;
const pages = Math.ceil(total / pageSize);
console.log(pages); // 6

Math.sqrt and Math.pow

Applies the Pythagorean theorem using Math.sqrt and Math.pow to compute a hypotenuse.

Example · js
function hypotenuse(a, b) {
  return Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
}
console.log(hypotenuse(3, 4)); // 5

Discussion

  • Be the first to comment on this lesson.
The Math Object — JavaScript | SoundsCode