Random Number Generator

Okay, hey! New script this week! This script is great in that it produces a random number between 1 and any number. You can set the upper limit within the script. The output of the script looks like this:

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.

Related Articles

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. Return to the script a rounded-off version (Math.round) of the upper_limit (not yet set), times (*) a random number between 0 and 1 (Math.random()). If the upper limit is set to 50, you would get one of 50 different answers, and since the round method rounds up, you'll never get a zero.

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.

Next Time: The Upper Limit

Please enable Javascript in your browser, before you post the comment! Now Javascript is disabled.