JavaScript ยท Chapter 25 of 55

JavaScript Math Object

The `Math` object provides constants and functions for mathematical operations, such as `Math.PI`, `Math.sqrt()`, `Math.abs()`, `Math.max()`, and `Math.min()`.

Unlike `Date`, `Math` is not a constructor โ€” you never write `new Math()`. You just call its static methods directly.

Common methods

`Math.round()`, `Math.floor()`, `Math.ceil()` handle rounding in different directions. `Math.max()` and `Math.min()` find extremes among arguments.

Powers and roots

`Math.pow(2, 3)` equals 8 (though `**` is now preferred). `Math.sqrt(16)` returns 4.

Example 1 (javascript)
console.log(Math.round(4.7));
console.log(Math.floor(4.7));
console.log(Math.ceil(4.2));
Output
5
4
5

round, floor, and ceil handle decimals differently.

Example 2 (javascript)
console.log(Math.max(3, 7, 2));
console.log(Math.min(3, 7, 2));
Output
7
2

max and min accept any number of arguments.

Key points

  • Math is a built-in object, not a constructor.
  • Math.round/floor/ceil round numbers differently.
  • Math.max() and Math.min() find extreme values.
  • Math.PI, Math.E are useful mathematical constants.
๐Ÿ’ก Note: Math.floor(Math.random() * n) is the classic pattern for a random integer from 0 to n-1.

๐Ÿ“ Quick Quiz

1. Which rounds a number down?

2. Do you need `new Math()`?

3. Math.max(3, 7, 2) returns: