2.11 Module 2 · Variables, Data Types & Functions

Math Functions

Explore the built-in Math object — JavaScript's built-in calculator for rounding, random numbers, powers, roots, and more.

1

Definition

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.

2

Simple Way

The Math object is like a calculator built into JavaScript — call its methods whenever you need number operations:

Math.random() Generate a random decimal between 0 (inclusive) and 1 (exclusive)
Math.floor() Round down to the nearest whole number — 4.9 → 4
Math.ceil() Round up to the nearest whole number — 4.1 → 5
Math.round() Round to the nearest integer — 4.5 → 5, 4.4 → 4
3

Code Examples

Example 1 — Math.random()
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());
Output
Click ▶ Run — the result changes each time!
Explanation
  • Returns a floating-point number ≥ 0 and < 1 — never exactly 1
  • Every call produces a different number — useful for games, shuffles, and simulations
  • On its own it is rarely useful — combine with Math.floor() to get integers
Example 2 — floor(), ceil(), round()
let 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
Output
Click ▶ Run to execute
Explanation
  • floor() — always goes to the lower integer, regardless of decimal
  • ceil() — always goes to the higher integer, regardless of decimal
  • round() — follows standard rounding: .5 and above rounds up, below rounds down
Example 3 — Random Integer in a Range
// 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
Output
Click ▶ Run — each result will be different!
Explanation
  • Math.random() * N produces a decimal from 0 to just below N
  • Math.floor() converts it to a whole number in the range 0 to N-1
  • Adding + min shifts the range upward — the general formula works for any bounds
Example 4 — max(), min(), abs(), pow(), sqrt()
console.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
Output
Click ▶ Run to execute
Explanation
  • Math.max() / Math.min() accept any number of arguments and return the largest or smallest
  • Math.abs() removes the sign — negative becomes positive
  • Math.pow(base, exp) raises a number to a power — same as the ** operator
  • Math.sqrt() returns the principal square root
Example 5 — Math Constants
console.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
Output
Click ▶ Run to execute
Explanation
  • Math.PI gives the most precise value of π available in JavaScript
  • toFixed(n) is a number method (not part of Math) that formats to n decimal places
  • Constants are all-caps properties — no parentheses, no arguments
4

Real-Life Example

Think of different everyday situations that map directly to Math methods:

Math.random()
Rolling a dice — a different result every time you call it
Math.floor()
Price rounding at a shop — ₹49.9 → ₹49 (always go lower)
Math.ceil()
Taxi fare rounding — ₹43.1 → ₹44 (always go higher)
Math.max()
Leaderboard — find the highest scorer from all players
Math.abs()
Distance — it is always positive, regardless of direction
Math.PI
Circle calculations — area, circumference, anywhere π is needed
5

HTML + JavaScript Example

Click ▶ Preview, then press Roll to simulate a dice — watch Math.floor(Math.random() * 6) + 1 produce a new result every time.

Live in Browser — Dice Roller
<!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>
Live Preview
6

Tasks (Practice)

Easy Task 1 — Random 0 to 5
Starter code
// Generate a random integer from 0 to 5
let value = Math.floor(Math.random() * 6);
console.log(value);
  • Run the code multiple times — confirm the output is always 0, 1, 2, 3, 4, or 5
  • Explain in a comment why multiplying by 6 gives the range 0–5
  • Change it to produce 0–9 by adjusting the multiplier
Medium Task 2 — Random 1 to 100
Starter code
// Use the general formula
function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

console.log(randomInt(1, 100));
  • Run the function several times — confirm results are always between 1 and 100
  • Use randomInt() to simulate rolling two dice and print their sum
  • Print Math.max() and Math.min() on the two dice values
7

MCQs

Q1
What is the range of values Math.random() can return?
// Run many times and observe
for (let i = 0; i < 5; i++) {
  console.log(Math.random());
}
Output
Run it to observe
  • A 0 to 10
  • B 1 to 10
  • C 0 (inclusive) to 1 (exclusive)
  • D -1 to 1
💡 C is correct. Math.random() returns a decimal ≥ 0 and strictly < 1 — it will never return exactly 1. Multiply and floor to get integers in any range.
Q2
What is the output?
console.log(Math.floor(4.9));
Output
Run it to verify
  • A 5
  • B 4
  • C 4.9
  • D Error
💡 B is correct. Math.floor() always rounds down — even 4.9 becomes 4, not 5. Use Math.round() if you want standard rounding.
Q3
What is the output?
console.log(Math.ceil(3.1));
Output
Run it to verify
  • A 3
  • B 4
  • C 3.1
  • D Error
💡 B is correct. 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.
8

Pro Tips & Extra Knowledge

  • 01

    The universal formula for a random integer between any min and max (both inclusive) — memorise this pattern:

    Universal random range formula
    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
    Output
    Click ▶ Run to execute
  • 02

    Use toFixed(n) on numbers — not part of Math, but essential for displaying calculations cleanly:

    Formatting decimal results
    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
    Output
    Click ▶ Run to execute
  • 03

    Use the spread operator (...) to pass an array into Math.max() or Math.min() — they don't accept arrays directly:

    max/min from an array
    let scores = [88, 95, 72, 100, 61];
    
    console.log(Math.max(...scores)); // 100 — spread unpacks the array
    console.log(Math.min(...scores)); // 61
    Output
    Click ▶ Run to execute
  • 04

    The ** exponentiation operator is a clean shorthand for Math.pow() — prefer it for simple power calculations:

    ** vs Math.pow()
    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
    Output
    Click ▶ Run to execute
Mini Challenge

What is the possible output range of this expression? Work it out before running — then run several times to confirm.

What values can this print?
let value = Math.floor(Math.random() * 5);

console.log(value);
Output
Run multiple times to see all possible values!
Step-by-Step Explanation
// 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