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

Don't Miss

  • Massive
    Ubisoft Massive exclusive: 'The Division', PS4 & Xbox One, Activision to Ubisoft & more
    Camera
    Games Exclusive
  • iPhone
    Get your wallet ready: The next iPhone could cost $100 more than your last one
    Video
    Tech Buzz
  • Civ
    Need to catch up on 'Sid Meier's Civilization'? Here is everything you need to know
    Camera
    Games Feature
  • Google Glass
    See how Google Glass is letting sick kids go to the zoo without leaving the hospital
    Tech News
  • Upcoming
    These are 2014's biggest PS4, Xbox One and Wii U games
    Camera
    Games Feature
  • Google
    Google has filed for a patent to develop contact lenses capable of taking photos
    Video
    Headlines

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 Examiner.com and apply today!