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.


Don't Miss

  • Division
    Ubisoft Massive exclusive: 'The Division', PS4 & Xbox One, Activision to Ubisoft & more
    Games Exclusive
  • Printer
    Zuta Labs’ portable printer is small enough to fit in a pocket, but can tackle full-size print jobs
    Tech Buzz
  • Dragon
    'Dragon Age: Inquisition' launches this October on PS4 and Xbox One, trailer inside
    Games News
  • Netflix
    Find out how much more you will be paying for the Netflix service in the near future
    Tech News
  • Upcoming
    These are 2014's biggest PS4, Xbox One and Wii U games
    Games Feature
  • Heartbleed
    The majority of Americans have not checked on their vulnerability to the Heartbleed bug

User login

Log in
Sign in with your email and password. Or reset your password.
Write for us
Interested in becoming an Examiner and sharing your experience and passion? We're always looking for quality writers. Find out more about and apply today!