HTML and CSS Reference
In-Depth Information
Dealing with variables
In JavaScript, a variable is simply a storage location and is not restricted to always storing values of
a fixed type. When assigned a value, variables take on the type of the data being stored. For this
reason, a JavaScript variable may change its type quite a few times during its lifespan, as shown in the
following code snippet:
var data = "dino"; // now data is of type string
data = 123; // now data is of type number
JavaScript variables spring into existence the first time they're used; until then, they hold a value of
null and their type is undefined .
Local variables
When defining variables, you should always use the var keyword as a hint to the parser and yourself.
The var keyword is not strictly required, but it is highly recommended to keep the scope of the
variable under strict control.
Variables defined within the body of a function are scoped to the function—and are therefore
local variables—only if they have been declared using the var keyword. If you omit var , variables are
treated as global, but remain undefined until the function executes once.
You should also note that JavaScript lacks the concept of block-level scope that you find in many
other programming languages. Consider the following code:
function foo(number) {
var x = 0; // Variable x is local to the function and not visible
outside
if (number >0) {
var y = number; // Variable y is NOT local to the IF block;
...
}
}
The variable y is not local to the if block, and its content is also accessible from outside the block.
However, because it is defined with var , the variable is local to the function. It is important to note
that if you miss the var keyword in the if block, what you might expect to be a temporary variable will
be promoted to the much higher rank of a global variable!
The same concept just shown for an if statement also applies to for and while loops.
Search WWH ::




Custom Search