DEV Community

Discussion on: How do you do random?

Collapse
 
joelnet profile image
JavaScript Joel • Edited

Math.random() produces a random float (all JavaScript numbers are of type float) from 0 to 1.

Adding the requirement of 0-10 means you have to multiply by 10 or * 10.

The last requirement was the number must be an Integer, which is the math.floor.

Of course, if you only wanted a random float between 0 and 1, it would be just one call.

And in PHP if you wanted a random float between 0 and 1, you would also have to do more work: Random Float between 0 and 1 in PHP

So the complexity actually comes from the requirements you give it.

But asking for a random integer is a common task. So it's handy to create function and keep it in your library. Don't go sprinkling Math.floor(Math.random() * 10) randomly around your codebase :D

const pseudoRandomInteger = (start, end) =>
  start + Math.floor(Math.random() * (end - start))

P.S. I prefixed this with pseudo because there is no true Random in JavaScript. This is very important when it comes to cryptography. Google PRNG if you want to learn more.

For a cryptographically strong random value, you might want to look into Crypto.getRandomValues()

Cheers!

Collapse
 
david_j_eddy profile image
David J Eddy
...the complexity actually comes from the requirement...

I wish PM's understood this more.

Collapse
 
krofdrakula profile image
Klemen Slavič

There's a bug in your example; if the output is supposed to be [start, end), then the correct implementation is:

const pseudoRandomInteger = (start, end) =>
  start + Math.floor(Math.random() * (end - start));

✌😉

Collapse
 
joelnet profile image
JavaScript Joel

I probably should have run it once. lol.

I gotta stop typing code directly into editors.

Good catch!

Collapse
 
jochemstoel profile image
Jochem Stoel
const between = (min, max) => Math.floor(Math.random() * max) + min