Javascript variable definitions

by Martin Westin in


The variable scope in javascript can still surprise me. This is a nice one I debugged today: A variable that is not defined by "var" have a global scope. This can be a real pain since the globalization is implicit and easy to forget.

I forgot the "var" when writing a for loop and could not for the life of me figure out what happened when the i-variable got mysteriously reset.

This is an example of a foor loop (in one()) that will never finnish since i is being reset in two(). Defining "var i=0" and all is well.

function one() {
	for (i=0;i<20;i++){
		if (i > 18) {
			two();
		}
	}
}
function two() {
	for (i=0;i<5;i++){
	}
	alert('two');
}