In this shot, we will learn to generate random numbers in JavaScript.
Math.random()
and Math.floor()
In JavaScript, the Math.random()
function generates random decimal numbers. The numbers generated are between 0, which is inclusive, and 1, which is exclusive. This means that the function can return 0 but not 1.
The Math. floor()
function rounds down a number to its nearest whole number.
The code below prints 12 to the console:
To generate whole numbers, we combine the function of Math.random()
with Math.floor()
. This means we generate a random number, then round it down to its nearest whole number.
To generate a whole number between 0 and 24:
Math.random()
function to generate a random decimal.Math.floor()
function to round down the number to its nearest whole number.We can see this in the code below, which will print numbers between 0 and 24 to the console:
We can generate random whole numbers that fall between two specific ranges of two numbers. A *minimum (min
) and a maximum number ( max
) are defined to get this.
We can use the formula below:
Math.floor(Math.random() * (max - min + 1) + min
The code above returns a whole number between 1 and 50.
Line 1: We create a function with two arguments, min
and max
. The formula for getting a random whole number within a range is passed to be printed in the console.
Line 2: We call the function.
RELATED TAGS
CONTRIBUTOR
View all Courses