Don't get this JS formula

Hey,

Somebody can explain that JS formula to me:

Math.floor(Math.random() * (max - min + 1)) + min

Please :slight_smile:.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/generate-random-whole-numbers-within-a-range

As should be obvious from the name of the challenge, it generates random integers within a range, namely between min and max. Math.random() generates a floating point number between 0 and 1 (exclusive, meaning it’s always less than 1). (max - min + 1) is one greater than the size of the range, so if you wanted to generate numbers between, say, 3 and 10, the size of the range you want to generate is 8, so when you multiply the random value by 8, now you’re generating random floats between 0 and 8 (exclusive). Now when you floor this number, you’ll get integers between 0 and 7. Then when you add min (3) to the result, you get integers between 3 and 10

I recommend experimenting with the formula on something like repl.it in order to get more understanding of it.

2 Likes

Hi @Tech, I’ve never followed up on any of @chuckadams answers before because he is so thorough but when I went through this it threw me for a loop too especially so because I knew a little JS and had used something similar in a couple of little apps I coded.
I say similar because I wasn’t going through a range, my code needed to start at one and include the final number so the expression I wrote was very similar.

What I did for this was literally go to Google and drop in that expression. Read through the first couple of hits that you get. Take a day to think about it and then come back and read the first few again and like he says, go to repl.it and try a few things using it. You’ll get that “ah-ha” moment.

1 Like

Alright thanks a lot :slight_smile:
I’ll do that.

Thanks a lot chuck it’s clearer now :slight_smile: