Saturday, November 17, 2018

JavaScript Random

Math.random()

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

Math.random();              // returns a random number

Math.random() always returns a number lower than 1.

JavaScript Random Integers

Math.random() used with Math.floor() can be used to return random integers.


Math.floor(Math.random() * 10);     // returns a random integer from 0 to 9

Math.floor(Math.random() * 11);      // returns a random integer from 0 to 10

A Proper Random Function

As you can see from the examples above, it might be a good idea to create a proper random function to use for all random integer purposes.
This JavaScript function always returns a random number between min (included) and max (excluded):

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




















Share:

0 comments:

Post a Comment

Contact Form

Name

Email *

Message *

Popular Posts

Blog Archive

Blog Archive

Hassan.mosmer1@gmail.com