Lesson 38 +15 XP

Random and Practical Use

Random and Practical Use

Math.random() is the starting point for randomness, but you usually need random numbers in a useful range.

Random integer 1 to 10

let n = Math.floor(Math.random() * 10) + 1;
  • * 10 spreads the range to 0-9.999.
  • Math.floor makes it 0-9.
  • + 1 shifts it to 1-10.

General formula

Random integer between min and max (inclusive):

function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

Pick from an array

const fruits = ["apple", "banana", "cherry"];
let pick = fruits[Math.floor(Math.random() * fruits.length)];

Random boolean (coin flip)

let flip = Math.random() < 0.5;

Where randomness helps

  • Games (dice, shuffling)
  • Choosing a random item
  • Testing and demos
  • Simple probability

TL;DR

  • Multiply and floor to get random integers.
  • Formula: floor(random * (max - min + 1)) + min.
  • Use array indexes for random picks.
  • Math.random() < 0.5 simulates a coin flip.