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

  • Unity
    'Assassin's Creed Unity' preview: Ubisoft comes home to its urban origins
    Games Preview
  • Smart vending machine
    This smart vending machine will recommend drinks for you based on your gender and age
    Video
    Tech Buzz
  • Destiny
    The 'Destiny' beta: 7 things we absolutely love about Bungie's new franchise
    Games Feature
  • Wi-Fi
    Find out how to stretch your Wi-Fi signal where it has never gone before
    Tech Tips
  • Far Cry
    'Far Cry 4' exclusive: Animals, avalanches, oxygen, side content and much more
    Games Interview
  • Gamer ghost
    Gamer finds and plays with ghost of deceased father on a classic game
    Video
    Headlines