math floor math random exclusive 0 inclusive 9 in javascript

To generate a random integer in JavaScript, exclusive of 0 and inclusive of 9, we can use the Math.floor() and Math.random() functions in conjunction with a simple formula:

index.tsx
// Generate a random integer between 1 and 10
var randomNum = Math.floor(Math.random() * 10) + 1;
98 chars
3 lines

Here, Math.random() generates a random number between 0 (inclusive) and 1 (exclusive), which we then multiply by 10 to get a number between 0 (inclusive) and 10 (exclusive). We then use Math.floor() to round down to the nearest integer, resulting in an integer between 0 (inclusive) and 9 (inclusive). Finally, we add 1 to shift the range up by one, resulting in an integer between 1 (inclusive) and 10 (inclusive).

gistlibby LogSnag