LanguagesJavaScriptThe Upper Limit

The Upper Limit

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.


The Tipster… Tip-O-Rama…

Once again we’re dealing with a random number script or set of scripts (it’s actually two). Here again is what the script’s output looks like followed by the script itself.

And here’s what it all looks like:

 

<script language="JavaScript">
<!--
function RandomNumber(upper_limit) 
{ 
return Math.round(upper_limit * Math.random()); 
}
//-->
</script>

<script language="JavaScript">
<!--
var upper_limit = 50;
document.write('Here is a random number between 0 and ' 
+ upper_limit + ':<P><center>');
document.write(RandomNumber(upper_limit) + '</center>');
//-->
</script> 


 


Why does this script post a number between 1 and 50? Well, mainly because you tell it to. The upper limit can be any number you want. Let’s look at the first of the two working scripts. Here’s the function statement:

 

function RandomNumber(upper_limit) 


Notice it follows the traditional function format except that the instance, those two parentheses, now have something written in them. That’s new, huh? That’s saying that the author wants this function to operate on that variable alone. By stating that, the author can give that variable a value later. In the case of this script, it’s a hard number written right into the code, but if you want you can set the variable to be filled in by a prompt. The prompt would pop up, ask the viewer which number should be the upper limit, and that number would be set as the “upper_limit” variable. Make sense?

Okay, so where do we get the upper limit? It comes in the second script in this line:

 


var upper_limit = 50; 


You could have probably guessed that, though. See how it’s set as a variable?

So, look at what is happening: You create a function that will manipulate numbers to get a random number somewhere between one and “something” by using a variable called “upper_limit.” That’s all loaded into the memory. Then the second script is enacted and the variable “upper_limit” is given a value. The function runs and a number is produced. It’s actually a pretty clever and compact way of doing things.

The question now is… how do those numbers and letters get to the page? It is a mystery that will have to wait until next week.

Next Time: document.write

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories