Skip to main content
  1. Tech
  2. Gadgets & Tech
  3. Internet

How to generate a random number from 1 to 10 in JavaScript

See also

JavaScript provides a built-in Math object to perform mathematical operations. The Math object provides many useful functions you can use. Two of these functions are random() and floor(). By combining these two functions, you can generate a random number from 1 to 10.

The random() function returns a random number from 0 to 1. Multiplying that number by 10 results in a random number from 0 to 9. Adding 1 to that result gives a random number from 1 to 10. Finally, you round that number down to the nearest integer with the floor() function. Here is the full equation that generates a random number from 1 to 10:

var num = Math.floor((Math.random()*10)+1);

It is easy to change the upper bound. To generate a random number from 1 to 50, just change 10 to 50:

var num = Math.floor((Math.random()*50)+1);

As you can see, it is easy to generate random numbers in JavaScript. The Math object does all the work. Now go see what else the Math object can do for you.

Happy coding!

For more articles, please subscribe, add or follow me here.

Advertisement