Codectionary / Developer documentation / JavaScript

Math Object: round, floor, ceil, abs, max, min, pow, sqrt

The Math object provides mathematical constants and functions as static methods - it is not a constructor, so you never create a Math instance. Common methods include rounding (round, floor, ceil, trunc), extremes (max, min), and power operations (pow, sqrt, cbrt).

Syntax

Math.round(num)
Math.floor(num)
Math.max(...nums)

Examples

Rounding Methods

The different ways to round a number, and how they differ.

console.log(Math.round(4.5));  // 5 - rounds to nearest, ties round up
console.log(Math.round(4.4));  // 4
console.log(Math.floor(4.9));  // 4 - always rounds down
console.log(Math.ceil(4.1));   // 5 - always rounds up
console.log(Math.trunc(4.9));  // 4 - simply removes the decimal part
console.log(Math.trunc(-4.9)); // -4 - different from floor for negatives

abs(), max(), and min()

Absolute value and finding extremes among values.

console.log(Math.abs(-5));       // 5
console.log(Math.max(3, 7, 2));  // 7
console.log(Math.min(3, 7, 2));  // 2

// Finding max/min in an array requires spread
const numbers = [4, 8, 2, 9, 1];
console.log(Math.max(...numbers)); // 9

pow() and sqrt()

Power and square root operations.

console.log(Math.pow(2, 3));  // 8 - same as 2 ** 3
console.log(2 ** 3);           // 8 - the ** operator is now preferred
console.log(Math.sqrt(16));    // 4
console.log(Math.cbrt(27));    // 3 - cube root

Best practices

  • Use the ** exponentiation operator instead of Math.pow() in modern code - it is more concise for the common case
  • Choose the right rounding method deliberately - round() for nearest, floor()/ceil() when you specifically need to always round down/up
  • Use Math.max(...array) with spread syntax to find the largest value in an array, since Math.max() itself takes individual arguments
  • Remember Math methods are all static - always call them as Math.round(), never new Math().round()

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation