See what's happening here? The link calls SayHi() which in turn calls GetName(). After GetName() executes, control goes back to SayHi() and the alert box pops up.

Now, there's an important rule that you should know about... a variable declared within a function is only available in that function. A variable declared outside of any function is available anywhere (global variable).

But, if you look at the function GetName(), you'll see the variable myname appears to be declared in a function, yet it is still available to the function SayHi(). How is that? Well, we didn't exactly "declare" myname... we just used it. Just using a variable makes it a global variable by default. It's then available to any function on the page. To actually declare a variable somewhere, you must preceed it with "var". To see the difference, alter the above example by declaring the variable myname within GetName()...

Kinda sorta don't work, right? So why did it work before? Because earlier, without an actual declaration using "var", the script just assumed it was a global variable... no matter where it was. In the preceeding example, we specifically declared the variable within the function, thereby causing it to no longer be a global variable.

So, why is this important? Why not make ALL variables global? Well, when you get into larger scripts, you'd have to be very careful naming your variables. Actually, you CAN make all variables global. We've been doing it all along. We just have a choice now. You could use a variable named "name" in ten different functions without the script confusing them, or inadvertantly changing their values.

All this talk about multiple functions and golobal vs local variables leads up to a very important concept... reusability. A reusable function is a function that performs a specific task, and is portable to many applications. You write a little snippet that does a certain something and whenever you need that certain something done, you just toss in the function and use it like a little tool.

There's a little piece of reusable code that I reuse all the time. It's my random number generator...

The function is condensed into one line for ease of use. I leave the comment above it as a reminder.

Whenever I want a random number between 1 and something, I simply call getRandom(something). (Needless to say I place this snippet somewhere in the script) If I want a random number between (and including) 1 and 100 I call getRandom(100).

Remember a while back we talked about prompt boxes returning a value? Well I made this particular function do just that. Notice the "return" statement? This function is written to return the random number. It doesn't just generate the random number, it actually sends it back to whatever called it.