The ECMAScript variables are loosely typed, and so-called loose types can be used to hold any type of data. In other words, each variable is just a placeholder for holding the value. To define a variable, use the var operator (Note that var is a keyword) followed by the variable name (that is, an identifier), as follows:
VAR message;
This line of code defines a variable named message that can be used to hold any value (such as an uninitialized variable, which holds a special value of--undefined.
Note that a variable defined with the var operator becomes a local variable in the scope that defines the variable. That is, if you use var to define a variable in a function, the variable is destroyed after the function exits, for example:
function Test () {
var message = "HI"; Local variables
}
Test ();
alert (message); Error!
Here, the variable message is defined using var in the function. When a function is called, the variable is created and assigned a value.
After that, the variable is destroyed immediately, so the next line of code in the example will cause an error. However, you can omit the var operator as follows to create a global variable:
function Test () {
message = "HI"; Global variables
}
Test ();
alert (message); "Hi"
This example omits the var operator so that the message becomes a global variable. Thus, once the test () function is called, the variable is defined and can be accessed anywhere outside the function.
Although it is possible to define global variables by omitting the VAR operator, this is not a recommended practice. Because global variables defined in local scopes are difficult to maintain, and if the Var operator is deliberately ignored, it can cause unnecessary confusion because the variables are not immediately defined. Assigning a value to an undeclared variable causes a Referenceerror error to be thrown in strict mode.
You can use a single statement to define multiple variables, as long as each variable (either initialized or uninitialized) is separated by commas as follows:
var message = "Hi",
Found = False,
Age = 29;
This example defines and initializes 3 variables. Also because ECMAScript are loosely typed, operations that use different types of initialization variables can be done in a single statement. Although line breaks and variable indentation are not required in the code, doing so can improve readability.
In strict mode, a variable named eval or arguments cannot be defined, or it can result in a syntax error.
"JavaScript advanced Programming" Reading notes---Variables