Calculate A Random Integer from 0 to n in Javascript

Calculate A Random Integer from 0 to n in Javascript

The solution for those of you who want me to cut the crap and need to calculate a random integer from 0 to n in Javascript.

// Where 2 is the max random number
Math.round(Math.random() * 2)
// This will randomly give you 0, 1, or 2

My Setup

The Problem

I was writing a React-Native game where I had multiple cards that would be presented to the player. To spice up the game I would ideally not start on the same card each and every time. I had approximately 100 cards so needed to create a random number from 0-100 to start on a random element of the card array.

// 100 is the max random number that will be returned
const card_number = Math.round(Math.random() * 100)
// Then I can pull my first element from the card array as follows
card_array[card_number]

The cards are unrelated so ideally we could pull 20 or 30 randomized cards, but that’s a but more complicated than having to calculate a random integer from 0 to n in Javascript and will get pushed to a later iteration. Check this article out if you’re having issues saving data to your local device! Happy coding!

Leave a Comment