Blog Archive

JavaScript generate Random number example

To generate a random number in JavaScript you have to use the Math.random() function. The JavaScript function Math.random() randomly generates a number from 0 to slightly less than 1.But our objective is to say generate a random number between 0 and 9999. So how do we achieve that? What we do is take the result of Math.random() and multiply that by 10000 which will result in something between 0 and slightly less than 10000 and then we use another function called Math.floor() to make that an integer. Math.floor() returns the largest integer less than or equal to a number.


Here is how to generate a random number between 0 and 9999

var randomValue = Math.floor(Math.random() * 10000);

Sample program with some useful random functions

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Generate a Random Number using Javascript</title>
<link rel="stylesheet" type="text/css" href="extjs/resources/css/ext-all.css">
<style type="text/css">
    body {
        margin: 10px 10px 10px 10px;
    }
</style>
<script type="text/javascript" src="extjs/ext-all-debug.js"></script>
<script type="text/javascript" src="random.js"></script>
</head>
<body>
   
</body>
</html>

Source for JavaScript file - random.js

Ext.Loader.setConfig({ 
    enabled: true 
});

Ext.application({
   
    name: 'MyApp',
    appFolder: 'app',
   
    launch: function() {
       
        //max 2 digit random number - between 0 and 99 
        console.log(this.getRandom(2));
        //max 5 digit random number - between 0 and 99999 
        console.log(this.getRandom(5));
        //get random number between 100 and 999 
        console.log(this.getRandomMinMax(100,999));
       
    },

    getRandom :  function(size) {
        return Math.floor(Math.random() * (Math.pow(10,size)));
    },

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

});