Over a million developers have joined DZone.

JavaScript For loops

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

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?



Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:

Published at DZone with permission of Veera Sundar, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}