Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 4. Working with Numbers and Math > Creating a Random Number Generator

recipe 4.4. Creating a Random Number Generator

4.4.1. Problem

You need to generate a random number, between 0 and 255.

4.4.2. Solution

Use a combination of JavaScript Math methods: random to generate a random value between 0 and 1, which is then multiplied by 255, and floor to truncate the number.

var randomNumber = Math.floor(Math.random() * 255);

4.4.3. Discussion

The random method generates a random number between 0 and 1. To increase the range, multiply the result by the upper end of the range of values you want. If you need a random number with a higher lower end, such as a number between 5 and 10, multiply the value from random by a number equal to the upper range, minus the lower range, minus 1, and then add the lower range to the result:

var randomNumber = Math.floor(Math.random() * 6) + 5;

The floor method rounds down the floating-point value to the nearest integer.

  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint