1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Random Numbers in JavaScript

Discussion in 'JavaScript and AJAX' started by pradeep, Jun 29, 2007.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:

    Introduction



    A random number generator (often abbreviated as RNG) is a computational or physical device designed to generate a sequence of numbers or symbols that lack any pattern, i.e. appear random. Computer-based systems for random number generation are widely used, but often fall short of this goal, though they may meet some statistical tests for randomness intended to ensure that they do not have any easily discernible patterns. Methods for generating random results have existed since ancient times, including dice, coin flipping, the shuffling of playing cards, and many other techniques.

    Here we'll see how to generate random numbers in JavaScript.

    How?



    The random() method function of the Math object allows you to get random numbers for various uses in your scripts. You can make a random quote generator or have another type of random script. The only trick is knowing how to get a random number within the boundary you want, and making it a random integer.

    Code:
     alert(Math.random()*50); // A random number
     

    Random Numbers within a range



    We would many times want a random number within a specified ranged, say between 1 and 10.

    Code:
     function rand(l,u) // lower bound and upper bound
     {
         return Math.floor((Math.random() * (u-l+1))+l);
     }
     
     //Usage
     alert(rand(3,6));
     
    You can also make it a method of the Math object like this,
    Code:
     Math.prototype.rand = function(l,u)
     {
         return Math.floor((Math.random() * (u-l+1))+l);
     }
     
     //Usage
     alert(Math.rand(1,10));
     
     

Share This Page