JavaScript: Generate Random Number in Range

Introduction

We as software developers often stumble into situations where we need to insert a dose of randomness into our code.

In this article, we will look at how to generate random numbers in JavaScript. We will also touch upon a few built-in methods to deal with random numbers. By the end, we will put this knowledge to good use by writing a function to simulate a six-sided die.

Generating Random Numbers in JavaScript

Math.random() in JavaScript generates a floating-point (decimal) random number between 0 and 1 (inclusive of 0, but not 1). Let's check this out by calling:

console.log(Math.random())

This will output a floating-point number similar to:

0.9261766792243478

This is useful if you're dealing with percentages, as any value between 0 and 1, rounded to two decimal places, can be thought of as a percentile.

Generating Random Whole Numbers in Range

We generally don't deal with floating-point numbers in the 0 to 1 range, though. So, let's look at a way to round floating-point numbers.

We can round down a floating-point number using Math.floor(). Similarly, we can round up a number via the Math.ceil() function:

console.log(Math.floor(3.6))
console.log(Math.ceil(3.6))

This will give us the output:

3
4

Let's generate a random number between min and max, not including max:

function randomNumber(min, max){
    const r = Math.random()*(max-min) + min
    return Math.floor(r)
}

Alternatively, we could've included max with the Math.ceil() function instead.

We are multiplying with (max-min) to transform the range [0,1) into [0, max-min). Next, to get a random number in the required range, we are adding min. Finally, we are rounding this to an integer using Math.floor().

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Let's call this method a few times and observe the results:

for (var i = 0; i < 10; i++) {
  console.log(randomNumber(0, 10))
}

This will output something similar to:

8
3
3
0
1
1
8
2
8
8

Conclusion

Generating pseudo-random numbers in a program can be used to simulate unpredictability of an enemy in-game, or for randomization of forests in a block-like game we all know and love. It can also be used to simulate random inputs while testing another program you wrote.

Either way, generating a random number is an important tool in any engineer's toolkit, and should be expanded as much as possible with different generation methods and algorithms. This article was just the first step of learning random number generation.

Last Updated: September 21st, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Abhilash KakumanuAuthor

Hey, I am a full-stack web developer located in India. I am a curious person who is always trying to wrap my head around new technologies. In my free time, I read novels and play with my dog!

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms