KIRUPA 🍊
KIRUPA 🍊
HomeArchiveLeaderboardAbout
Sign in

Let's talk about random numbers! 📠

KIRUPA 🍊's avatar
KIRUPA 🍊
Apr 11

 

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 😃

Discussion about this post

User's avatar

Keep reading

KIRUPA 🍊

Thought provoking and educational content that lives at the intersection of design 🎨, development 🤖, and business 💰.

  • About
  • Archive
  • Recommendations
  • Sitemap
© 2026 KIRUPA 🍊 · Privacy ∙ Terms ∙ Collection notice
Start your SubstackGet the app
Substack is the home for writing, podcasting, and media founders.