Monday, September 27th, 2010

JavaScript For loops

One of the commonly used code fragment amongst any developer is for(i=0; i<end;i++). We use this style of for loop for iterating collections of arrays and just for some repeating functionality. But sometimes, even this simple for loop might bring you troubles if you are not careful.

Consider the below code. It calls a demo.methodOne when the document finished loading. The JS methodOne contains a simple for loop which should iterate 5 times and then alert “Hello World!” each time it iterates. After the alert message, methodOne makes a call to methodTwo.

<html>
	<head>

	<script type="text/javascript">
	var demo = {
		methodOne:function(){
			for(i=1; i<=5; i++){
				alert("Hello World!");
				demo.methodTwo();
			}
		},

		methodTwo:function(){
			for(i=1; i<=5; i++){
				// do nothing.
			}
		},
	};
	</script>
	</head>
	<body onload="javascript:demo.methodOne()">
	</body>
</html>

Just by looking at the code, one should expect the alert message to be displayed 5 times. But it won’t. Instead, the message will be displayed just once.

Can anyone explain why and what would be the right code to fix it? If no one answering, I’ll be posting an update soon. :)

{ 3 comments… read them below or add one }

Vishnu September 27, 2010 at 11:57 pm

The variable ‘i’ shared by the both functions. we have to declare the variable ‘i’ once again for the methodTwo.

var demo = {
methodOne:function(){
for(i=1; i<=5; i++){
demo.methodTwo();
}
},

methodTwo:function(){
for(var i=1; i<=5; i++){
// do nothing.
}
},
};

Reply

Veera September 28, 2010 at 12:04 am

exactly.

Reply

Vinay Raikar. September 28, 2010 at 12:08 am

The problem is with the variable scope. As the variable `i` has not been declared with `var i`, the variable `i` assumed to be global and methodTwo changes it to 5. And when it returns back, value of `i` is 5 and hence it exits from loop.
The variable `i` should be declared with `var` keyword in each for loop so that it is taken as a local variaable. The correct code is at http://jsbin.com/iwepi5.

Reply

Leave a Comment

Previous post:

Next post: