Random number generator

Math.random()

The JavaScript Math object has some useful methods we can use to perform mathematical tasks on numbers.

Math.random() returns a random number between 0 (inclusive) and 1 (exclusive):

Example

console.log(Math.random()); 
console.log(Math.random()); 
console.log(Math.random());

Returns some random numbers such as:

0.9638357574572449
0.8104676046927597
0.7326529015948489

If you want a random number from 0 to 10, you can get it with simple math:

Math.random() * 10

Random integers

When designing games we often need to generate random integers, for example, to randomly draw a card from a deck. Math.random() and Math.floor() together can be used to generate random integers.

Math.floor(Math.random() * 10);

The above code generates a random integer from 0 to 10 (exclusive), or from 0 to 9 (inclusive). There are totally 10 possible results. In order to get an integer from 1 to 10, we can simply add 1 to the result:

Math.floor(Math.random() * 10) + 1;

In general, if we want a random integer between min and max (exclusive):

Math.floor(Math.random() * (max - min)) + min;

A User-defined random integer function

As you can see from the examples above, we can define a function to generate random integers.

This JavaScript function always returns a random integer between min (included) and max (excluded):

Function randInt()
function randInt(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
}

Use the new function randInt() to get some random integers:

console.log(randInt(3, 8);       // 5
console.log(randInt(10, 20);     // 12
console.log(randInt(30, 40);     // 25

results matching ""

    No results matching ""