HTML and CSS Reference
// Global variable
var name="Daniel"; // Local variable
alert("In function the name is " + name +
" and hometown is "+ hometown );
greetme(); // Function call
alert("Out of function, name is "+ name +
" and hometown is " + hometown );
The variables called name and hometown are global in scope. They are visible
The function called greetme() is declared and defined.
Any variables declared within a function with the var keyword are local to that
function. In fact, you must use the var keyword when declaring local variables;
otherwise, the variables will be global. The variable called name has been declared
inside the function. This is a local variable and has nothing to do with the global
variable of the same name on line 1. The function variable will go out of scope;
that is, it will no longer be visible, when the function ends on line 6, at which
point the global variable will come back in scope. If the variable, name , had been
given a different name, within the function, such as name2 or myName , then the
global variable would have remained in scope within the function.
The variable called name and hometown were defined inside this function and are
local in scope. They will stick around until the function exits.
The closing curly brace marks the end of the function definition.
The function greetme() is called here.
The global variable called name has come back into scope.
The global variable called hometown is still in scope (see Figure 7.8).