Over a million developers have joined DZone.

JavaScript For loops

DZone's Guide to

JavaScript For loops

· Web Dev Zone ·
Free Resource

Jumpstart your Angular applications with Indigo.Design, a unified platform for visual design, UX prototyping, code generation, and app development.

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.


	<script type="text/javascript">
	var demo = {
			for(i=1; i<=5; i++){
				alert("Hello World!");

			for(i=1; i<=5; i++){
				// do nothing.
	<body onload="javascript:demo.methodOne()">

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?

Take a look at an Indigo.Design sample application to learn more about how apps are created with design to code software.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}