Software Sue

Link to Simply Sue
Link to Sustainability Sue
location: software/scripting/javascript/variables Skip navigation : Home  

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:

Subsequent characters may be:

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