Learn Create Your Own Split Screen

Next Page

That's all a bit verbose, so we can use our knowledge about functions to make a convenient way to obtain a random number between 0 and some limit.

function RandInt(up_to) { n = Math.floor(Math.random() * up_to); return(n); }

The above code defines a new function I've chosen to call RandInt. When used, it expects to be given a number that I've called up_to. The function then calculates a random integer between zero and 'up_to' (whatever value it happens to have at that time), and stores it in another variable which I've called 'n'. The last line tells the function to return the value of 'n' as the result.

With that function now defined, I can use it like so:

var thing= RandInt(50);
After that line of code, 'thing' will contain a random integer from 0 to 49, inclusive.

I could have added one, and made it between 1 and 50, but for reasons that will soon becomes apparent, doing it this way will suit our purpose better.