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" "">
<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;
<script type="text/javascript" src="extjs/ext-all-debug.js"></script>
<script type="text/javascript" src="random.js"></script>

Source for JavaScript file - random.js

    enabled: true 

    name: 'MyApp',
    appFolder: 'app',
    launch: function() {
        //max 2 digit random number - between 0 and 99 
        //max 5 digit random number - between 0 and 99999 
        //get random number between 100 and 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;


No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.