To generate a random number in JavaScript, you can use the Math.random() function. This function returns a floating-point number between 0 and 1 (excluding 1). You can multiply the result by the range you want and add the minimum value to generate a number within the desired range.
Here is an example code block that generates a random integer between 1 and 100 inclusive:
index.tsx161 chars7 lines
In the example code, the getRandomInt
function takes two arguments, min
and max
, which define the range of the random number. The Math.floor
function rounds the multiplied result down to the nearest integer, which gives us an integer between the specified range. Finally, we add the min
value to shift the range to the desired minimum value.
Using the getRandomInt
function with arguments 1
and 100
, we can generate a random integer between 1 and 100, and assign it to the randomInt
variable. The code then logs the value of randomInt
to the console.
gistlibby LogSnag