Saturday, February 26, 2011

VARIABLES-DECLARING AND USING


VARIABLES:
You use variables as symbolic names for values in your application. You give
variables names by which you refer to them and which must conform to certain
rules.
A JavaScript identifier, or name, must start with a letter or underscore (“_”);
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).
Some examples of legal names are Number_hits, temp99, and _name.

DECLARING VARIABLES:


You can declare a variable in two ways:
• By simply assigning it a value. For example, x = 42
• With the keyword var. For example, var x = 42
Evaluating Variables
A variable or array element that has not been assigned a value has the value
undefined. The result of evaluating an unassigned variable depends on how
it was declared:
• If the unassigned variable was declared without var, the evaluation results
in a runtime error.
• If the unassigned variable was declared with var, the evaluation results in
the undefined value, or NaN in numeric contexts.


The following code demonstrates evaluating unassigned variables.
function f1() {
return y - 2;
}
f1() //Causes runtime error
function f2() {
return var y - 2;
}
f2() //returns NaN
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 as a Boolean value. For
example, the following code executes the function myFunction because the
array element is not defined:
myArray=new Array()
if (!myArray[0])
myFunction()
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
n * 32 //returns 0

VARIABLE SCOPE:

When you set a variable identifier by assignment outside of a function, it is
called a global variable, because it is available everywhere in the current
document. When you declare a variable within a function, it is called a local
variable, because it is available only within the function.
Using var to declare a global variable is optional. However, you must use var
to declare a variable inside a function.

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.


No comments:

Post a Comment

Tweet