References

Beginner-friendly references for web development, with live, editable examples.

The JavaScript Math object

Object JavaScript All modern browsers Updated
Quick answer

The Math object is a built-in namespace of math functions and constants. You call its methods directly — Math.random(), Math.round(), Math.floor(), Math.max(), Math.abs() — without creating an instance. It also holds constants like Math.PI.

Overview

Math is a little different from the other built-ins: it's not a constructor you create with new, but a static namespace — a collection of math functions and constants you call directly on Math. There's no such thing as a Math instance; you just write Math.sqrt(16).

The everyday stars are the rounding and random helpers. Math.round(), Math.floor() and Math.ceil() turn decimals into integers in different directions; Math.random() generates randomness; Math.max() and Math.min() find extremes; and Math.abs() strips the sign. Beyond those you'll find Math.pow() (or the ** operator), Math.sqrt(), Math.trunc(), the trig functions, and constants such as Math.PI and Math.E.

Two reminders that come up constantly. Math.random() is not cryptographically secure — never use it for tokens or passwords; use crypto.getRandomValues() for that. And since Math functions operate on the single Number type, the usual floating-point caveats apply, so round results when you display them.

Syntax

Math.round(4.6);      // 5
Math.floor(4.6);      // 4
Math.ceil(4.1);       // 5
Math.max(3, 9, 1);    // 9
Math.abs(-7);         // 7
Math.sqrt(16);        // 4
Math.PI;              // 3.14159...
Math.random();        // 0 <= n < 1

Example

Live example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
  const data = [3.7, 9.2, 1.5, 6.8];

  document.getElementById('out').textContent =
    'max:    ' + Math.max(...data) + '\n' +
    'min:    ' + Math.min(...data) + '\n' +
    'rounded:' + data.map(n => Math.round(n)).join(', ');
</script>

Best practices

  • Call methods directly on Math — it's a namespace, never instantiated with new.
  • Use Math.floor() with Math.random() for random integers.
  • Spread arrays into Math.max()/Math.min(): Math.max(...nums).
  • Never use Math.random() for security — use crypto.getRandomValues().

Frequently asked questions

Do I need to create a Math object?
No. Math is a static namespace — you call its methods directly, like Math.sqrt(9), with no new.
How do I generate a random number?
Use Math.random() for a decimal from 0 to 1, then scale and Math.floor() it for an integer range.
What is the difference between Math.round, floor and ceil?
round() goes to the nearest integer, floor() always down, and ceil() always up.
How do I raise a number to a power?
Use Math.pow(base, exp) or the exponentiation operator base ** exp.