Generate a random number between two numbers in JavaScript

0 min read 140 words

If you need to generate a random number between two numbers in JavaScript, then you are in the right place! Here you will learn javascript random number generation.

We can easily do this by using a combination of built-in Math functions.

Javascript Random Number from Math.random()

Let’s start by using Math.random() to generate a random number. Now we will take that and multiply it by max - min + 1.

Because of how the Math.random() function works, we will need to then add the minimum value to this.

Once we are done, we pass it through a Math.floor() to get an absolute integer value (not a float).

Code example for Javascript Random Numbers

We can wrap this all into a function as follows:

var generateRandomNumberBetween = function(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
};
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags