Skip to content

Math Object

The built-in Math object provides constants and static methods for numeric operations β€” rounding, trigonometry, random numbers, min/max, and more. Unlike most JS objects, you never instantiate Math β€” you call its methods directly, e.g. Math.round(), not new Math().

console.log(Math.round(4.5)); // 5
console.log(Math.floor(4.9)); // 4
console.log(Math.ceil(4.1)); // 5
console.log(Math.abs(-7)); // 7
console.log(Math.max(3, 7, 2)); // 7
console.log(Math.min(3, 7, 2)); // 2
console.log(Math.pow(2, 10)); // 1024 (also: 2 ** 10)
console.log(Math.sqrt(16)); // 4
// Random integer between min and max (inclusive)
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomInt(1, 6)); // simulates a dice roll

Assuming Math.random() includes the upper bound, or forgetting Math.floor() when generating a random integer β€” Math.random() returns a float in [0, 1), so without flooring you get a float, and without the +1 adjustment your range excludes the max value.

// Bug: returns a float, not an integer, and never quite reaches `max`
function randomInt(min, max) {
return Math.random() * (max - min) + min;
}
// Correct: floors to an integer and includes both min and max
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
  1. What range of values does Math.random() return?

    AnswerA float from 0 (inclusive) up to but not including 1 β€” [0, 1).
  2. What’s the difference between Math.floor() and Math.round() for 4.5?

    AnswerMath.floor(4.5) gives 4 (always rounds down); Math.round(4.5) gives 5 (rounds to the nearest integer, halves round up).
  3. How do you generate a random integer between 1 and 6 (inclusive), like a dice roll?

    AnswerMath.floor(Math.random() * 6) + 1