Explore the built-in Math object — JavaScript's built-in calculator
for rounding, random numbers, powers, roots, and more.
The Math object in JavaScript is a built-in object that provides mathematical constants and functions for performing calculations such as rounding numbers, generating random values, finding maximums and minimums, and computing powers and square roots.
Unlike most objects, Math is not a constructor — you never write
new Math(). All its properties and methods are accessed directly
as Math.random(), Math.PI, and so on.
The Math object is like a calculator built into
JavaScript — call its methods whenever you need number operations:
0 (inclusive) and 1 (exclusive)
4.9 → 4
4.1 → 5
4.5 → 5, 4.4 → 4
let value = Math.random();
console.log(value); // e.g. 0.7342...
// Run multiple times — you get a different number each time
console.log(Math.random());
console.log(Math.random());
0 and < 1 — never exactly 1Math.floor() to get integerslet num = 4.6;
console.log(Math.floor(num)); // 4 — always rounds DOWN
console.log(Math.ceil(num)); // 5 — always rounds UP
console.log(Math.round(num)); // 5 — rounds to nearest
console.log(Math.floor(4.1)); // 4
console.log(Math.ceil(4.1)); // 5
console.log(Math.round(4.4)); // 4
console.log(Math.round(4.5)); // 5
floor() — always goes to the lower integer, regardless of decimalceil() — always goes to the higher integer, regardless of decimalround() — follows standard rounding: .5 and above rounds up, below rounds down// 0 to 9 (10 possible values)
let zeroToNine = Math.floor(Math.random() * 10);
console.log(zeroToNine);
// 1 to 6 — simulating a dice roll
let dice = Math.floor(Math.random() * 6) + 1;
console.log("Dice rolled:", dice);
// General formula: min to max (inclusive)
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomInt(10, 20)); // between 10 and 20
Math.random() * N produces a decimal from 0 to just below NMath.floor() converts it to a whole number in the range 0 to N-1+ min shifts the range upward — the general formula works for any boundsconsole.log(Math.max(10, 20, 5)); // 20 — largest value
console.log(Math.min(10, 20, 5)); // 5 — smallest value
console.log(Math.abs(-15)); // 15 — absolute (positive) value
console.log(Math.pow(2, 8)); // 256 — 2 to the power of 8
console.log(Math.sqrt(144)); // 12 — square root of 144
Math.max() / Math.min() accept any number of arguments and return the largest or smallestMath.abs() removes the sign — negative becomes positiveMath.pow(base, exp) raises a number to a power — same as the ** operatorMath.sqrt() returns the principal square rootconsole.log(Math.PI); // 3.14159... — pi
console.log(Math.E); // 2.71828... — Euler's number
// Practical use — area of a circle
let radius = 7;
let area = Math.PI * Math.pow(radius, 2);
console.log("Area:", area.toFixed(2)); // rounded to 2 decimal places
Math.PI gives the most precise value of π available in JavaScripttoFixed(n) is a number method (not part of Math) that formats to n decimal placesThink of different everyday situations that map directly to Math methods:
Click ▶ Preview, then press Roll to simulate a dice — watch
Math.floor(Math.random() * 6) + 1 produce a new result every time.
<!DOCTYPE html>
<html>
<head><title>Dice Roller</title></head>
<body style="font-family:sans-serif;padding:24px;background:#f8f9fa;text-align:center">
<h2>Dice Roller</h2>
<div id="dice"
style="font-size:5rem;margin:16px 0;min-height:80px;line-height:1">
🎲
</div>
<p id="label" style="color:#555;font-size:1rem;margin-bottom:16px">
Press Roll to start
</p>
<button onclick="rollDice()"
style="padding:10px 28px;background:#f7df1e;border:none;border-radius:6px;
cursor:pointer;font-weight:700;font-size:1rem">
Roll
</button>
<div id="history"
style="margin-top:20px;font-size:0.9rem;color:#555;line-height:1.8">
</div>
<script>
const faces = ["⚀","⚁","⚂","⚃","⚄","⚅"];
let rolls = [];
function rollDice() {
let result = Math.floor(Math.random() * 6) + 1; // 1–6
rolls.push(result);
document.getElementById("dice").textContent = faces[result - 1];
document.getElementById("label").textContent =
`Rolled: ${result} | Max so far: ${Math.max(...rolls)} | Min: ${Math.min(...rolls)}`;
document.getElementById("history").textContent =
"History: " + rolls.join(", ");
}
</script>
</body>
</html>
// Generate a random integer from 0 to 5
let value = Math.floor(Math.random() * 6);
console.log(value);
0, 1, 2, 3, 4, or 56 gives the range 0–50–9 by adjusting the multiplier// Use the general formula
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomInt(1, 100));
1 and 100randomInt() to simulate rolling two dice and print their sumMath.max() and Math.min() on the two dice valuesMath.random() can return?
// Run many times and observe
for (let i = 0; i < 5; i++) {
console.log(Math.random());
}
Math.random() returns a decimal ≥ 0 and strictly < 1 — it will never return exactly 1. Multiply and floor to get integers in any range.
console.log(Math.floor(4.9));
Math.floor() always rounds down — even 4.9 becomes 4, not 5. Use Math.round() if you want standard rounding.
console.log(Math.ceil(3.1));
Math.ceil() always rounds up — even 3.1 becomes 4, not 3. Think of it as "ceiling" — you always go to the next floor above.
The universal formula for a random integer between any min and max (both inclusive) — memorise this pattern:
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomInt(1, 6)); // dice: 1–6
console.log(randomInt(0, 100)); // percentage: 0–100
console.log(randomInt(50, 99)); // custom range: 50–99
Use toFixed(n) on numbers — not part of Math, but essential for displaying calculations cleanly:
let price = 199.9;
let discount = 0.15; // 15%
let final = price - price * discount;
console.log(final); // 169.915 — too many decimals
console.log(final.toFixed(2)); // "169.92" — clean display
Use the spread operator (...) to pass an array into Math.max() or Math.min() — they don't accept arrays directly:
let scores = [88, 95, 72, 100, 61];
console.log(Math.max(...scores)); // 100 — spread unpacks the array
console.log(Math.min(...scores)); // 61
The ** exponentiation operator is a clean shorthand for Math.pow() — prefer it for simple power calculations:
console.log(2 ** 10); // 1024 — clean syntax
console.log(Math.pow(2, 10)); // 1024 — identical result
console.log(3 ** 3); // 27
console.log(Math.sqrt(256)); // 16 — sqrt still uses Math
What is the possible output range of this expression? Work it out before running — then run several times to confirm.
let value = Math.floor(Math.random() * 5);
console.log(value);
// Step 1: Math.random()
// Returns a decimal in [0, 1) — e.g. 0.0, 0.3, 0.7, 0.9999...
// It will NEVER be exactly 1
// Step 2: Math.random() * 5
// Scales the range to [0, 5) — e.g. 0.0, 1.5, 3.5, 4.9999...
// It will NEVER be exactly 5
// Step 3: Math.floor(...)
// Drops the decimal, always rounds DOWN
// Possible results: 0, 1, 2, 3, 4
// Output range: 0 to 4 (5 possible values)
// NOT 0 to 5 — because Math.random() never reaches 1,
// the product never reaches 5, so Math.floor() never gives 5.
// To get 0 to 5 (6 values): Math.floor(Math.random() * 6)
// To get 1 to 5 (5 values): Math.floor(Math.random() * 5) + 1