JavaScript: Loops

Sometimes in JavaScript, you want to repeat a piece of code a number of times. Not necessarily forever (although maybe forever), but more likely, until a certain condition is true. This functionality can be accomplished through structures called 'loops'.

While loops

One of the simplest loops in JavaScript is called the 'while' loop. This is accomplished by writing the keyword while, followed by the condition/expression that must remain true for the loop to keep looping in brackets, followed by the code you want executed every time the loop goes round in curly brackets -- it's much like an 'if statement' only it uses the keyword while, and loops round the code until the condition is false. Something like the following would work fine for an infinite loop:

1
2
3
4
while(true)
{
	alert('Spamming this at you!');
}

As alluded to, the above loop obviously continues forever since the condition, true, will always be true. It's very common to use an what is called an "iterator variable" to control how many times a loop should loop around. You can create this just like a normal variable, and then utilise it in the condition - for example the following:

1
2
3
4
5
var i = 0; //Iterator variable called 'i'
while(i < 5)
{
	alert('Do something here');
}

The current issue with the above code, is that as it is, it still runs forever. This is because 'i' (which starts at 0) will never be 5 or more. So to change this and make the condition eventually return false (and hence make the loop eventually end), we can do what is called 'incrementing'. This sounds way more confusing than it is, but is essentially just adding 1 to something - in this example, we simply want to add 1 to 'i' every time the loop goes round. An example of this is the following:

1
2
3
4
5
6
var i = 0; //Iterator variable called 'i' as this stands for 'iterator'
while(i < 5)
{
	alert(i);
	i = i + 1;
}

On running this code with the incrementation, you should now see that the loop runs 5 times and that the alert boxes read '0', '1', '2', '3', '4'. You can also increment a variable by using the += operator (which adds the value on the right of it, to that on the left - so something like i += 1) or even better by simply adding the ++ operator to the end of the variable name, so in our example:

1
2
3
4
5
6
var i = 0; //Iterator variable called 'i' as this stands for 'iterator'
while(i < 5)
{
	alert(i);
	i++;
}

Sometimes it's also useful to have loops which count down - this can be accomplished by simply modifying the condition and iterator variable, and taking away one from the number each time. This act of taking away 1 from something is called decrementing. Much like incrementing, decrementing could be accomplished using a basic equals operator like variable = variable - 1;, using the -= operator (which behaves like +=), or in my opinion the cleanest way, using the decrement operator: -- (similar to ++). The following is an example of a loop which counts down:

1
2
3
4
5
6
var i = 5; //Iterator variable called 'i' as this stands for 'iterator'
while(i > 0)
{
	alert(i);
	i--;
}

You'll notice that this also loops 5 times (and the alert boxes output '5', '4', '3', '2', '1'). It's worth keeping in mind that you can formulate the condition exactly like you would in an 'if statement' - so you can use logical operators and different conditional operators if you need a more complex loop.

Another common use of 'while' loops is repetition until the user does something. This often uses the boolean data-type - this is a data-type which can either be set to 'true' or 'false' (see the code below). An example of this functionality would be prompting the user to enter a number between 0 and 100 until they do this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var userInput;
var userInputIsCorrect = false;

while(!userInputIsCorrect)
{
	userInput = prompt('Enter a number between 0 and 100');
	if(userInput >= 0 && userInput <=100)
	{
		userInputIsCorrect = true;
	}
	else
	{
		alert('You didn\'t enter a value between 0 and 100 - please try again.');
		userInputIsCorrect = false;
	}
}
alert('Thank you for inputting a value between 0 and 100.');

If you test this out - you should see that it will repeatedly ask the user to input a number between 0 and 100 until they do so! If you don't quite understand how the code above works, make sure you have a strong knowledge of 'if statements', logical operators, and of course, 'while' loops.

'For' loops

There is also another kind of loop called a for loop. This is much like a 'while' loop, however instead of having to increment a variable each time, we can embed this functionality inside the loop structure itself which makes these types of loops much easier to use when looping for a certain number of times.

We first type the for keyword and then in brackets we have to write three different important pieces of information for the loop, separated by 2 semicolons, and then we specify the code to loop in curly brackets. So the concept should look something like the following:

1
2
3
4
for(something;something;something)
{

}

The first part of the loop is called the initialization. This is executed once at the beginning of the loop, and should be used to set a variable to a certain value. It's usually used to set the iterator variable's value to something (most of the time to 0). The second part is called the condition - this is simply the condition that must be maintained for the loop to keep looping. Finally the third part is called the iteration expression - it will be executed once every time the loop loops and should be used to change the condition in some way (usually effecting the iterator variable in some way - often incrementing or decrementing). For example the following:

1
2
3
4
5
var i;
for(i=0;i<5;i++)
{
	//Code to loop 5 times here
}

So in the above case we are setting our iterator variable 'i' to 0 in the initialization part of the 'for' loop, we are checking if 'i' is less than 5 in the condition part of the 'for' loop, and we are incrementing 'i' in the iteration expression part of the 'for' loop.

You can obviously modify each section of the loop as you see fit. To demonstrate that the 'for' loop actually works and I'm not just making stuff up (after all, I'm just a random guy on the internet - why should you trust me?) - you could put something like the following into a JS file which is included into an HTML file (for example the project folder that we setup at the start of these tutorials) or use this JSFiddle iframe: