Let's talk about random numbers! 📠
![](https://substackcdn.com/image/fetch/w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fbucketeer-e05bbc84-baa3-437e-9518-adb32be77984.s3.amazonaws.com%2Fpublic%2Fimages%2F1b044f88-623e-413e-8a29-2dae4a066415_1200x400.png)
Hi, *|USERNAME|*!
Large parts of our apps and sites will have behavior that is fully predictable and predefined. There will be cases where our app will deliberately exhibit some randomness. We could have an animation whose speed, direction, or other characteristics will be randomly defined. We may want to generate a query string or a random GUID to store some state or bypass caching. We may have a billion and a half reasons for wanting some randomness, but JavaScript definitely doesn't make generating the random values we want easy. To help with this, you may like the Random Numbers in JavaScript article that I recently posted.
When it comes to random numbers in JavaScript, the main thing to keep in mind is that the Math.random() function returns a value between 0 and a number less than 1. This means to properly generate a number between a low value and a high value, the formula looks as follows:
Math.floor(Math.random() * (1 + High - Low)) + Low
This looks a little bizarre and convoluted, but to help highlight that this totally works, take a look at this random number frequency visualizer. This visualizer generates a number between 1 and 5, and it does this by running 1400 times. Notice the numbers that get generated with each run:
Each number between 1 and 5 occurs about an equal number of times. That's a good indication that we have a good formula for calculating a random number between two values.
TILL NEXT TIME!
Working with random numbers is something that I have a lot fun doing. I would love to hear from you on when you use random numbers in your code. Don't be shy! The easiest way to share your affinity for random numbers is to ping me via Twitter or by posting on the forums.
Cheers,
Kirupa 😃