Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript random() method

JavaScript random() method

Math Object Reference JavaScript Math object

Example

Returns a random number between 0 (inclusive) and 1 (exclusive):

Math.random();

Output result:

Try it »


Definition and Usage

The random() method returns a random number between 0 (inclusive) and 1 (exclusive).


Browser support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

All major browsers support the random() method


Syntax

Math.random()

Return Value

Type Description
Number A pseudo-random number between 0.0 and 1.0 (exclusive).

Technical Details

JavaScript version: 1.0

More examples

Example

In this example, we will get a random number between 1 and 10:

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

Output result:

Try it »

Example

In this example, we will get a random number between 1 and 100:

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

Output result:

Try it »

Example

The following function returns a number between min (inclusive) and max (exclusive):

function

getRndInteger

(

min

,

max

)

{

return

Math

.

floor

(

Math

.

random

(

)

(

max

min

)

)

min

;

}

Try it »

Example

The following function returns a number between min (inclusive) and max (inclusive):

function

getRndInteger

(

min

,

max

)

{

return

Math

.

floor

(

Math

.

random

(

)

(

max

min

1

)

)

min

;

}

Try it »


Math Object Reference JavaScript Math object