concepts

Math Object

JavaScript Math object provides properties and methods for mathematical operations.

Math

  • Math.PI returns 3.14159

  • Math.round(1.2) rounds to the nearest integer

  • Math.floor(1.2) rounds down to the nearest integer

  • Math.ceil(1.2) rounds up to the nearest integer

  • Math.sqrt(100) returns the square root of x

  • ...and many more.

Math Object vs. Math Operations

  • Object: for specialized/complex mathematical operations and constants (e.g., Math.PI).

  • Operations: built-in operators for basic calculations like addition, subtraction, multiplication, etc.

Example — basic operations:

basic-operators.js
let sum = 5 + 3;          // Addition
let difference = 10 - 4;  // Subtraction
let product = 6 * 7;      // Multiplication
let quotient = 15 / 3;    // Division
let remainder = 10 % 3;   // Modulus (remainder)
let power = 2 ** 3;       // Exponentiation (ES2016+)

Example — Math object usage:

random() method

Math.random() returns a pseudo-random number between 0 (inclusive) and 1 (exclusive).

  • Math.random() gives you a random decimal number between 0 and 1

  • Includes 0 but never exactly 1

  • No parameters. Method is called without any arguments

    • ✅ Correct: Math.random()

    • ❌ Incorrect: Math.random(123)

You can scale the result by multiplying:

To convert to integers, use rounding:

  • Rounding down with Math.floor(Math.random() * 10) returns integers 0, 1, 2, ... 9

  • Rounding up with Math.ceil(Math.random() * 10) returns integers 0, 1, 2, ... 10

circle-info

Remember: multiplying Math.random() by N yields a decimal in [0, N). Rounding behavior determines the inclusive/exclusive range for integers.

References

  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math

  • https://codehs.com/tutorial/ryan/math-object-in-javascript

  • https://javascript.info/number#other-math-functions