Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
15 views

JavaScript Random

The document discusses how to generate random numbers and integers in JavaScript using Math.random() and Math.floor(). It provides examples of using Math.random() to return a random number between 0 and 1 and random integers between a specified min and max range by combining it with Math.floor().

Uploaded by

Pace Infotech
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

JavaScript Random

The document discusses how to generate random numbers and integers in JavaScript using Math.random() and Math.floor(). It provides examples of using Math.random() to return a random number between 0 and 1 and random integers between a specified min and max range by combining it with Math.floor().

Uploaded by

Pace Infotech
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

JavaScript Random

Math.random()

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

Example

// Returns a random number:


Math.random();

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.

There is no such thing as JavaScript integers.

We are talking about numbers with no decimals here.

Example

// Returns a random integer from 0 to 9:


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

Example

// Returns a random integer from 0 to 10:


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

Example

// Returns a random integer from 0 to 99:


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

Example

// Returns a random integer from 0 to 100:


Math.floor(Math.random() * 101);
Example

// Returns a random integer from 1 to 10:


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

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):

Example

function getRndInteger(min, max) {


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

You might also like