Random function in java script – How it works?

Random frunction in JS

Random function in JS

Overview: In this article we will discuss about randomizing function in java script. Random content generation is one of the major functions implemented through java script. This is not only random number generation but also used to generate any content, calculation, image selection etc.








Introduction: The random function in java script is used to generate some random content at runtime. The most common example of this feature is to generate random numbers on the fly. The random () method of the Math object enables us to get random numbers at runtime. The random function in the Math object returns a random number between zero and one.

How it works:

Generating a random content on a web page can be divided into three sections:

  • Define the entity
  • Define the randomize function
  • Use the randomize function to get the desired entity

Define the entity:

In this section, we generate a random quote, which is required to define a long list of quotes. These quotes will be used by the script to pick one at a time. This is achieved by using an array which is a one dimensional matrix used to store every possible piece of information. From this array the randomizing function will pick the random (in this case) quote. Let us consider the following code snippet:

Listing 1: creating the random quote array

[code]

quotes = new Array
(
” This is quote 1 “,
” This is quote 2 “,
” This is quote 3 “,

” This is the last quote ”
) ;

[/code]

As we can see this is a simple way in which we define an array in java script. We create this array with some fixed quotes.

Define the randomize function:  

Once the array from where the random entity is picked, is defined, we need a function which delivers a random result to pick the said entity. There are many ways to do this. The following code snippet uses the timestamp to pick a random entity from the array:

Listing 2: creating the random function

[code]

rnd.today = new Date();
rnd.seed = rnd.today.getTime();

function rnd()

{
rnd.seed = ( rnd.seed*9301+49297 ) % 233280;
return rnd.seed/ (233280.0);
} ;

function rand( number )
{
return Math.ceil( rnd () * number );

};

[/code]

Here, the first two lines are used to define two elements, based on the date and time. These elements are used in the next line, which is the function rnd (). This function is defined basically as a little sum which uses the time and date as used before which in turn is then used in the function rand (number) to define a function that will return a random number based on the time and date.







Displaying the random entity:

Once the random function is defined, it is quite simple to return a random entity. A simple call to the script to write the quote associated with the number generated by the random function:

Listing 3: call to the random function

[code]

document.write( quotes[ rand( quotes.length )-1 ] )

[/code]

Here, rand is the function as defined above, (quotes. Length)-1 is the range of quotes we have defined in the array and document.write is the JavaScript command that returns the “value” which is generated within the parenthesis. It is then this entity, which will be displayed on the webpage. Now let’s have a look into the entire script:

Listing 4: the full source code

[code]

quotes = new Array
(
” This is quote 1 “,
” This is quote 2 “,
” This is quote 3 “,

” This is the last quote ”
) ;

rnd.today = new Date();
rnd.seed=rnd.today.getTime();

function rnd()

{
rnd.seed = ( rnd.seed*9301+49297 ) % 233280;
return rnd.seed / ( 233280.0 );
};

function rand(number)
{
return Math.ceil(rnd()*number);

};

document.write( quotes[ rand( quotes.length )-1 ] )

[/code]

Finally we as a developer have to decide where to include this code in our html page. Here we have two options:

  • within the html page which we will be using or
  • write a separate script and call the function when the page is loaded

If we use the first option we need to include the script tag within the html header or body as under:

Listing 5: include the source code within the html page

[code]

<script type = ” text / javascript ” >

// The script code goes here

</script>

[/code]

This option should be used in situation where the script is used only for a given circumstance. This is not the generic approach. Moreover we cannot re-use the script if required. The second option is more generic approach and supports the re-usability feature. Here the function is written in a .js file which is called when the page is loaded. This is done as under:

Listing 6: include the js file

[code]

<script type = ” text / javascript ” src = ” myscript.js “>
</script>

[/code]








Using the Math random function:

The random () method of the Math object enables us to get random numbers at runtime. The random function in the Math object returns a random number between zero and one. We can make a random quote generator or have another type of random script. The most important part here is to know the range within which we want to get the random integer. By default, the random function returns a random number between zero and One. This is not very useful if we want to have a random number between zero and another number e.g. 5. In this case we achieve our target if we multiply the output of Math.random() function by 5. This is done as under:

Listing 7: get the random number between 0 and 5.

[code]

var ran_number =  Math.random() * 5;

[/code]

The above code will get the random number between 0 (included) and 5 (excluded) but the generated numbers will not be integers. If we need to have the integer values we need to change the above code as under:

Listing 7: get integer the random number between 0 and 5

[code]

var ran_number_unrounded =  Math.random() * 5;

var ran_number = Math.floor( ran_number_unrounded )

[/code]

Now consider the following code snippet:

Listing 8: a complete html code along with javascript function using randomization

[code]

<HEAD> <SCRIPT language=”JavaScript”><!–function get_random(){    var ranNum = Math.floor(Math.random()*5);    return ranNum;} function getaQuote(){   var whichQuote = get_random();     var quote = new Array(5)     quote[0] = ” I love JavaScript..sometimes. “;     quote[1] = ” Why are you pushing my button? “;     quote[2] = ” The button you pushed can\’t push you back. You bully, you! “;        quote[3] = ” This alert is here to inform you that alerts are annoying. “;     quote[4] = ” Which came first, the button or the alert? “;     alert(quote[whichQuote]);  }//–></SCRIPT></HEAD> <BODY><FORM name = ” form1 “><INPUT TYPE = ” button ” value = ” Get a Quote! ” onClick = ” getaQuote() “></FORM>   </BODY>

[/Code]

Here the function get_random () returns a random number between 0 and 4 (both included). The next function, getaQuote () uses the random number generated by this function as an array index and returns the message from the array.

Summary: To conclude this discussion we can keep the following points in mind while using random function. It is implemented in wide are of functionalities in modern web applications and portals.

  • Random Function is used to generate random content at runtime
  • The process of generating random content can be divided into three sections :
    • define the entity
    • define the function
    • get the desired entity using the random function
  • The most common used example is getting a random number at runtime.
Tagged on:
============================================= ============================================== Buy best TechAlpine Books on Amazon
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share