Tsallaka zuwa abun ciki
Justice Tech School

Random Numbers

Math.random() returns a decimal from 0 up to (but not including) 1. Multiply and floor it to get a whole number in a range. These numbers are fine for games and shuffling but not for passwords or security.

Example
function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
const roll = randomInt(1, 6);
console.log(roll >= 1 && roll <= 6);
const colors = ["red", "green", "blue"];
const pick = colors[Math.floor(Math.random() * colors.length)];
console.log(colors.includes(pick));

Exercise

Get a random decimal between 0 and 1.

Math.()

Quiz Test

Is Math.random() suitable for generating passwords?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.