random number in javascript

To generate a random number in JavaScript, you can use the Math.random() function which returns a decimal number between 0 and 1 (exclusive of 1). To get a random number within a specific range, you can use the following formula:

index.tsx
Math.floor(Math.random() * (max - min + 1)) + min
50 chars
2 lines

Where max is the maximum value, min is the minimum value, and Math.floor() rounds the number down to an integer.

Here is an example of how to generate a random number between 1 and 10:

index.tsx
const randomNum = Math.floor(Math.random() * 10) + 1;
console.log(randomNum); // Outputs a random number between 1 and 10
122 chars
3 lines

gistlibby LogSnag