generate a random number between 1 and 100 in javascript

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.tsx
const randomNumber = Math.floor(Math.random() * 100) + 1;
58 chars
2 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