To generate a random number between 1 and 100 in JavaScript, we can use the Math.random() method. This method returns a random number between 0 (inclusive) and 1 (exclusive). We can then multiply this number by 100 and add 1 to get a random number between 1 and 100.
index.tsx58 chars2 lines
The Math.floor()
method is used to round down the generated number to the nearest integer, ensuring that the output is a whole number between 1 and 100. Adding 1 to the result is necessary because the Math.random()
method returns a number between 0 and 0.999..., and multiplying this by 100 will result in a range between 0 and 99.999... Adding 1 ensures that the final result falls within our desired range.
gistlibby LogSnag