Math Object
Overview
The Math object is a built-in static object in JavaScript that has properties and methods for mathematical constants and functions.
Unlike other global objects like Date or Array, the Math object is not a constructor. You cannot use the new keyword with it (new Math() will throw an error). All properties and methods of Math are static, meaning you call them directly on the Math object itself.
Syntax
console.log(Math.round(4.6)); // 5 (Rounds to nearest integer)
console.log(Math.round(4.4)); // 4
console.log(Math.ceil(4.1)); // 5 (Always rounds UP)
console.log(Math.floor(4.9)); // 4 (Always rounds DOWN)
// Truncate simply removes the decimals
console.log(Math.trunc(4.9)); // 4console.log(Math.min(0, 150, 30, 20, -8, -200)); // -200
console.log(Math.max(0, 150, 30, 20, -8, -200)); // 150
// Math.random() returns a decimal between 0 (inclusive) and 1 (exclusive)
console.log(Math.random());
// Generating a random integer between 1 and 10:
const random10 = Math.floor(Math.random() * 10) + 1;Common Pitfalls
Math.random()never returns exactly 1. It returns0 <= x < 1. If you need a random integer up to 10, you must multiply by 10, then useMath.floor(), then add 1.
Interview Questions
new Math()?Because Math is not a constructor function. It is a static namespace object that simply holds mathematical constants and helper functions.
Math.max() takes a comma-separated list of arguments, not an array. To pass an array, you must use the spread operator: Math.max(...myArray).
Real-World Example
Generating a random 6-digit OTP (One Time Password) for two-factor authentication.
function generateOTP() {
// Generates a random number between 100000 and 999999
return Math.floor(100000 + Math.random() * 900000);
}Check Your Knowledge
Test your understanding of Math Object with these quick questions.