JavaScript and Variables
Variables
You use variables as symbolic names for values in your application. The names of variables, called identifiers, conform to certain rules.
A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($); subsequent characters can also be digits (0-9). Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase).
Starting with JavaScript 1.5, you can use ISO 8859-1 or Unicode letters such as å and ü in identifiers. You can also use the uXXXX Unicode escape sequences as characters in identifiers.
Some examples of legal names are: Number_hits, temp99, and _name.
Declaring variables
You can declare a variable in two ways:
With the keyword var. For example, var x = 42. This syntax can be used to declare both local and global variables.
By simply assigning it a value. For example, x = 42. This always declares a global variable and cannot be changed at the local level. It generates a strict JavaScript warning. You shouldn't use this variant.
Evaluating variables
A variable declared using the var statement with no initial value specified has the value undefined.
An attempt to access an undeclared variable will result in a ReferenceError exception being thrown:
var a;
console.log("The value of a is " + a); // logs "The value of a is undefined"
console.log("The value of b is " + b); // throws ReferenceError exception
You can use undefined to determine whether a variable has a value. In the following code, the variable input is not assigned a value, and the if statement evaluates to true.
var input;
if(input === undefined){
doThis();
} else {
doThat();
}
The undefined value behaves as false when used in a boolean context. For example, the following code executes the function myFunction because the myArray element is not defined:
var myArray = new Array();
if (!myArray[0]) myFunction();
The undefined value converts to NaN when used in numeric context.
var a;
a + 2 = NaN
When you evaluate a null variable, the null value behaves as 0 in numeric contexts and as false in boolean contexts. For example:
var n = null;
console.log(n * 32); // Will log 0 to the console
Variable scope
When you declare a variable outside of any function, it is called a global variable, because it is available to any other code in the current document. When you declare a variable within a function, it is called a local variable, because it is available only within that function.
JavaScript does not have block statement scope; rather, it will be local to the code that the block resides within. For example the following code will log 5, because the scope of x is the function (or global context) within which x is declared, not the block, which in this case is an if statement.
if (true) {
var x = 5;
}
console.log(x);
Another unusual thing about variables in JavaScript is that you can refer to a variable declared later, without getting an exception. This concept is known as hoisting; variables in JavaScript are in a sense "hoisted" or lifted to the top of the function or statement. However, variables that aren't initialized yet will return a value of undefined.
/**
* Example 1
*/
console.log(x === undefined); // logs "true"
var x = 3;
/**
* Example 2
*/
// will return a value of undefined
var myvar = "my value";
(function() {
console.log(myvar); // undefined
var myvar = "local value";
})();
The above examples will be interpreted the same as:
/**
* Example 1
*/
var x;
console.log(x === undefined); // logs "true"
x = 3;
/**
* Example 2
*/
var myvar = "my value";
(function() {
var myvar;
console.log(myvar); // undefined
myvar = "local value";
})();
Because of hoisting, all var statements in a function should be placed as near to the top of the function as possible. This best practice increases the clarity of the code.
Global variables
Global variables are in fact properties of the global object. In web pages the global object is window, so you can set and access global variables using the window.variable syntax.
Consequently, you can access global variables declared in one window or frame from another window or frame by specifying the window or frame name. For example, if a variable called phoneNumber is declared in a FRAMESET document, you can refer to this variable from a child frame as parent.phoneNumber.
Constants
You can create a read-only, named constant with the const keyword. The syntax of a constant identifier is the same as for a variable identifier: it must start with a letter, underscore or dollar sign and can contain alphabetic, numeric, or underscore characters.
const prefix = '212';
A constant cannot change value through assignment or be re-declared while the script is running.
The scope rules for constants are the same as those for variables, except that the const keyword is always required, even for global constants. If the keyword is omitted, the identifier is assumed to represent a variable.
You cannot declare a constant with the same name as a function or variable in the same scope. For example:
// THIS WILL CAUSE AN ERROR
function f() {};
const f = 5;
// THIS WILL CAUSE AN ERROR ALSO
function f() {
const g = 5;
var g;
//statements
}
Comments 0