by Joe Burns, Ph.D.

Mr. Tip, I presume?
And here's what it all looks like:
<script language="JavaScript"> Wait (you yell)! That's not one script, that's two!
But they work with each other. The first script actually creates the random number. The second is mainly there to set the upper limit and display the results. It's a pretty clever script. Look at the line that creates the random number to start it off.
Let's break it down so it's readable. "Math" is an object, but it's a strange object. It itself isn't really anything except a socket with which you can connect methods. It's just that when you use the Math object, you are stating to the browser that this script deals directly with numbers and mathematics. "round" (note lack of capitalization) is a method that rounds off the number that "Math" will soon represent. "random" (again, note lack of caps) is a method that asks for a random number between 0 and 1. Keep in mind that JavaScript plays in millisections so it's not as silly as it first seems. There are 1000 choices the script can make.
So, let's read the line. Make a note of where all the parentheses are. The upper limit number and the random number between 0 and 1 are figured first. Then the number is rounded. Remember that from high school algebra? What's inside the ( ) gets figured first. That's the mathematics of it all. But where does the upper limit come from? Why, it's the function itself! See you next week.
Learn to write your own JavaScripts with the HTML Goodies 30-Step Primer Series and take the knowledge home with you in JavaScript Goodies! You can find many other uses for JavaScripton your Web pages here! |