JavaScript Tutorial - Variables and Scope

Left
Right

A variable is something that "varies". In that it can carry a value that can be changed. Contrast this to constants, that do not change at all.

JavaScript is a un-typed language - that is - a variable can hold either an integer, floating point, string, or an object at anytime regardless of what it held before.

The only provision is that you "must" declare variables before reading them. (This results in a run-time error if not done.)

Scope is the term to describe where the variable is defined.

  • Global scope - the variable is available everywhere (and in functions) and exist for the entire program duration.
  • Local scope - the variable is visible only in the function or block, not outside. The variable only lasts as long as the function is being executed and is gone when the function finishes.
    (Later we will discuss "static" variables that are local to a function, but keep their values between function calls.)
  • local variables can mask global variables making them invisible to the function.

Example: work/vars.html

<HTML>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
// integers
var i;		// un-initialized
var j = 3;	// initialized to a value
// floating point
var pi = 3.1419;
// string
var global = "global";
var string = global;

document.writeln("<BR>global scope");
document.writeln("<BR>i = ", i);
document.writeln("<BR>j = ", j);
document.writeln("<BR>pi = ", pi);
document.writeln("<BR>global = ", global);
document.writeln("<BR>string = ", string);

function f() {
	var string = "local";	// initialized in local scope
	var i = 5;		// initialized in local scope
	j = 5;			// set in global scope
	document.writeln("<BLOCKQUOTE><BR>In function f()");
	document.writeln("<BR>global = ", global);
//	document.writeln("<BR>local = ", local); // this is a run-time error
	document.writeln("<BR>string = ", string);
	document.writeln("<BR>i = ", i);
	document.writeln("<BR>j = ", j);
	k = 5;			// this declares and initializes k
				// however,not a good practice
	document.writeln("<BR>k = ", k);
	document.writeln("<BR>Out of function f()</BLOCKQUOTE>");
}
f();	// call the function

document.writeln("<BR>global scope");
document.writeln("<BR>i = ", i);
document.writeln("<BR>j = ", j);
document.writeln("<BR>pi = ", pi);
document.writeln("<BR>global = ", global);
document.writeln("<BR>string = ", string);

</SCRIPT>
</BODY>
</HTML>
Left
Right
Slide 4