generate a random number between 2 and 15 in javascript

You can generate a random number between 2 and 15 in javascript using the following code:

index.tsx
var randomNumber = Math.floor(Math.random() * 14) + 2;
55 chars
2 lines

Explanation:

  • Math.random() generates a random number between 0 and 1.
  • We want to generate a number between 2 and 15, so we need to multiply the random number by the range we want, which is 14 (15 - 2 + 1).
  • Math.floor() rounds down the result to the nearest integer.
  • Finally, we add 2 to shift the range from 0-13 to 2-15.

The randomNumber variable will now hold a random integer between 2 and 15.

gistlibby LogSnag