Snippet. JavaScript. Generate Random Number

This JavaScript snippet shows how to return a random number. A randomly generated number is necessary in multiple occasions. For instance, games of chance (dice,backgammon,lucky numbers, etc).

Function random_number

The function random_number returns a randomly generated number. It accepts one argument specifying the maximum size of the returned number.The minimum returned number is 0.

function random_number(range){
    return Math.floor(Math.random() * range);
}

Example

var rnum = random_number(64);

alert("Your lucky number is " + rnum);

Test


Updated on: 23 Nov 2024