JavaScript

Variables

Variables are used as symbolic names for values in your application. The name (JavaScript Identifier) you give then must conform to the following rules:

Names must begin with:		a letter (A-Z or a-z) or an underscore ("_")
Subsequent characters may be:	digits (0-9), letters (A-Z and/or a-z) or underscores ("_")

For example:			My_variable, year21, _variabubble.

Declaring Variables

To declare a variable, either:

Unassigned Variables

If a variable or array element has not been assigned a value, it takes the value undefined. If it was declared without var, evaluating the variable results in a runtime error. If it was declared with var, evaluating the variable results in the undefined value, or NaN in numeric contexts. So, for example:


function f1() { return y - 2; }		f1() //Causes runtime error
In practice, got invalid character in IE, no error in Netscape 4.6

function f2() { return var y - 2; }	f2() //returns NaN
In practice, got invalid character in IE, no error in Netscape 4.6

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){	// In NN4.6 input is undefined as
   document.writeln("Undefined");	// I haven't assigned a value.
} else {			// In IE4 you get an error as
 document.writeln("Defined");	// 'undefined' is undefined.
}

When used as a Boolean value, the undefined value behaves as false, for example:


anotherArray=new Array()
if (!anotherArray[0])
 document.writeln("Undefined")

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

Scope of Variables

A variable is global if you assign it outside of a function, and local if you assign it inside. A global variable is available everywhere in the current document, and using var in the declaration is optional. Var is mandatory for declaring variables within functions.

To access a global variable declared in one window or frame from another, specify the other window or frame. For example, after declaring a global variable called customerName in a FRAMESET document, you can refer to it as parent. CustomerName from a child frame.

Back to top     Home     Serious Stuff

© 2001. Copyright Sue Nethercott.