Jump to content

Subtle error in JavaScript tutorial


Guest ZeroG

Recommended Posts

Guest ZeroG

I just noticed a slight error in the JavaScript tutorial in the JS Variables section:

Assigning Values to Undeclared JavaScript VariablesIf you assign values to variables that has not yet been declared, the variables will automatically be declared.These statements:
x=5;carname="Volvo";

have the same effect as:

var x=5;var carname="Volvo";

I discovered after quite a bit of work that it's not quite that simple. Actually, JavaScript will declare variables as globals if you don't use the var statement - otherwise, it observes scope rules basically the same way C does. As an example, consider the following code:
	function outer() {		for (i = 0; i < 5; i++) {			document.write("outer: " + i + "<br />");			inner();		}	}		function inner() {		for (i = 0; i < 3; i++) {			document.write("inner: " + i + "<br />");		}	}		outer();

If you execute this (I tried in IE 7 and FF 2), you will get an infinite loop and your browser will ask you to stop the script. The output is:

outer: 0inner: 0inner: 1inner: 2outer: 4inner: 0inner: 1inner: 2outer: 4inner: 0inner: 1inner: 2outer: 4...

As you can see, the i in outer keeps getting set to 3 after inner exits, and then it gets incremented to 4 every time. However, if you use var i = 0 instead of just i = 0, it works as expected. Just a suggestion - you might want to put some kind of note in the variable section that not using var makes JavaScript declare variables as global. I didn't know that until last week, and it might be good for folks just starting out to know that.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...