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 like PI

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+)
  • Operations for built-in operators for calculations like add, subtract, multiply, etc.

let squareRoot = Math.sqrt(16);        // Square root
let rounded = Math.round(4.7);         // Rounding
let randomNumber = Math.random();      // Random number
let piValue = Math.PI;                 // Mathematical constant
let maxValue = Math.max(5, 10, 15);    // Finding maximum
let sineValue = Math.sin(Math.PI/2);   // Trigonometry

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)

  • Multiply Math.random() times * integer returns random decimimal number between 0 and x

    • e.g. Math.random() * 10 returns decimal between 0 and 9.999 infinitely, but never 10

  • Round up/down to get whole numbers

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

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

References

Last updated