|
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.
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>