Variables in JavaScript


There are two types of variables.

The scope of a variable is the area or region in which a variable is usable. Thus a local variable is only usable within the function within which it is declared. Note that JavaScript does not require explict declaration of variables (Visual Basic and Perl will allow this. Although Perl does weird and unexpected things with what are called local variables). Therefore care must be taken when using non-explicitly declared variables in JavaScript. For instance, once could declare a local variable in a function. One could also use the same variable name outside of the function. It is important to note that the variable used outside the function will not have the same value as that of the variable in the function. I have not as yet tried this but that is the general theory anyway. Non explicity declared variables are generally a bit of a nightmare for highly disciplined programmers.

The script shown below declares name1 and name2 globally. str and Mesg are declared locally to the Msg function. name1 and name2 are set to Joe and Harry respectively. Setting of name2 inside the function resets name2 to Larry since name2 is a global variable. Changing Mesg outside the function has no effect. In fact there will be a second declaration of Mesg outside the function. There are actually two declarations of Mesg within the HTML page. One is global to the entire page. The other is active only in the function. In fact the global declaration of Mesg is ignored inside the function. Once again, that is the theory. How theory applies in JavaScript I am not as yet sure of.

Click the link below to see the script in action.

...

var name1 = "Joe";
var name2 = "Harry";
function Msg (str)
{
	var Mesg = "Hi ";
	document.writeln (Mesg + str);
	name2 = "Larry";
}

...

Msg (name1);
Msg (name2);
Msg (name2);
Mesg = "Goodmorning ";
Msg (name1);

...
Run the Script above.