Back to article index

Javascript global and local variable scope

2007-08-06IT Mill


With Javascript there is so easy to create errors and bugs by mistake. You don't even have to be a very careless coder to make functions to fail. Here is a demonstration of one interesting feature of the language.

Tip: use firebug to see what happens.

Test #1:

Normally when you read the value of global variable you get what you expect:

// Introduce a global variable and assign a value for it
var myVar =  "GLOBAL"

function testOne() {
	alert("myVar evaluates to '"+myVar+"'");
}

Test #2:

Now, things get interesting if you later in the same function introduce a new variable with the same name. The local variable masquerades the global variable in whole function:

// Introduce a global variable and assign a value for it
var myVar =  "GLOBAL"

function testTwo() {
	// Display value of global variable
	alert("myVar evaluates to '"+myVar+"'");

	// Create local variable myVar with different value
	var myVar = "LOCAL";
	alert("myVar evaluates to '"+myVar+"'");
}

Test #3:

Here is an example how one might mess with local and global variables. First developer tries to change global variable, and later in the function he/she introduces local variable. Now myVar in the beginning points to local variable in whole function and the global assignment behaves unexpectedly.

// Introduce a global variable and assign a value for it
var myVar =  "GLOBAL"

function testThree() {
	// assign value of global variable myVar
	myVar = "NEW_GLOBAL_VALUE";
	alert("myVar evaluates to '"+myVar+"'");

	// Create local variable myVar with different value
	var myVar = "LOCAL";
	alert("myVar evaluates to '"+myVar+"'");
}

A Conclusion

It does not matter where in function you introduce the local variables. Local variable "myVar" is (kind of) known to exist in func1 before it is introduced. It is an example how things can go wrong (especially if one have hundreds of lines of code).





Back to article index


Add Your Comment

Comments, corrections and suggestions about the content of this article are always welcome.