Game Lab Documentation

Math.random

Category:Math

You will find many opportunities in your apps to utilize random numbers. This function can help you achieve that!

Examples

Example: random number

Returns a random floating-point number that is greater than or equal to 0 and less than 1 (0 <= num < 1).

// Generates a random number in the range (0 <= randNum < 1) and prints it to the console
var randNum = Math.random();
console.log(randNum);

Example: random number 2

Returns a floating-point random number that is in the range (0 <= randNum < 5).

// Generates a random number in the range (0 <= randNum < 5) and prints it to the console
var randNum = Math.random() * 5;
console.log(randNum);

Example: random number 3

Returns a floating-point random number that is in the range (0 <= randNum < 10). Then, it rounds the number to an integer, rounding up on a decimal value of .5 or higher, and rounding down if not.

// Generates a random number in the range (0 <= randNum < 10), rounds it to a whole number, and prints it to the console
var randNum = Math.random() * 10;
randNum = Math.round(randNum);
console.log(randNum);

Syntax

Math.random

Returns

Returns a random floating-point number that is greater than or equal to 0 and less than 1 (0 <= num < 1). It returns a result with approximately uniform distribution over that range.

Tips

  • You will often need to make use of other mathematical operators (+, -, *, /) in order to create a random number in the range that you desire (see examples below)
  • The number returned is not truly random as defined in mathematics but is pseudorandom.

Found a bug in the documentation? Let us know at support@code.org.