Generating random numbers with JavaScript (Part 2)

I had posted the first part of my article on Hashnode with context to generating random numbers in JavaScript, when you have a decimal or a whole number. Hope you all have checked it out!

In the second part, I will be focusing on generating a random whole number that falls within the range of two specific numbers. To understand this further, we will define a minimum and a maximum number respectively — lets call it as ‘min’ and ‘max’.

JavaScript provides us with a mathematical formula and how it can be integrated in our code snippet as described below:

function randomRange(ajMin, ajMax) {
 return Math.floor(Math.random() * (ajMax — ajMin + 1)) + ajMin;
}

var display = randomRange(3,20);
console.log(display);

The above code created a function named randomRange and passes ajMin, ajMax as my custom parameters, describing a minimum and a maximum number within the range. With the formula specified along with the return statement, the function will return a random number which will be greater or equal to ajMin (inclusive) and less than or equal to ajMax (inclusive).

We will then call the randomRange() function by passing 3, 20 as my custom arguments and saving the result in the display variable. You can view your answer by using console.log() function which outputs a random number within the range of 3–20 (both numbers inclusive).

Note: While exploring this concept further, as an example, I used decimal numbers within the range itself and observed that I was getting the output in the same decimal format. As a best practice (specially for novice programmers), I would recommend using whole numbers when you encounter this function in your learning paths of basic JavaScript and practicing it along as well.

Hope you find this article insightful!

Happy Coding!