dimanche 19 juillet 2020

Random Range function/formula in JavaScript

I was learning JavaScript in freecodecamp.org, Basic JavaScript. In the stage 103/110 there was a task to create a function which takes 2 arguments (minimum value and maximum value) and the function should return a random number between them. The formula was given and I did the task and completed it, but I didn't quite understand why the formula works.

function randomRange(myMin, myMax) {
  return Math.floor(Math.random() * (myMax - myMin + 1) + myMin);
}
console.log(randomRange(10, 20))

This is the code.

and this is the formula Math.floor(Math.random()*(max - min + 1) + min. Can you please explain the formula and why does this work?

This is the task link. I guess you might have to login to see this.




Aucun commentaire:

Enregistrer un commentaire