HomeToolsAbout a20k

Math

Math.random()

static method returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1

  • approximately uniform distribution over that range
  • you can then scale to your desired range

Scaling to desired range

function getRandomInt(max) { return Math.floor(Math.random() * max); } console.log(getRandomInt(3)); // Expected output: 0, 1 or 2

Scale shifting to desired min range

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

Security Concerns

Math.random() does not provide cryptographically secure random numbers

  • Do not use them for anything related to security
© VincentVanKoh