Programming & Scripting Tutorials

Javascript: Loops

Sometimes in Javascript, you want to repeat something. Not necessarily forever (although perhaps you want to loop forever), but perhaps until a certain is true.
These can be accomplished through what are called 'loops'.

While loops

One of the simplest loops is called a 'while' loop.
This is one of the loops in Javascript, and is accomplished by writing the keyword 'while', followed by the condition that must remain true for the loop to keep looping, 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 this:

while(true)
{
	alert('Spamming this at you!');
}


In the above case, the loop obviously continues forever since the condition will always be true. It's very common to use an what's called an “iterator variable" to control how many times a loop should loop round. You can create this just like a normal variable, and then put it in the condition – for example:

var i = 0; //Iterator variable called 'i' as this stands for 'iterator'
while(i < 5)
{
	alert('Do something here');
}


The issue with the above code, is that as current – 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) – we can do what is called 'incrementing. It sounds way more confusing than it is, but it's basically just adding 1 to something – in this example, we simply want to add 1 to 'i' every time the loop runs.
For example:

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 incrementing, 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) or even better – by simply adding '++' at the end of the variable, so in our example:

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


Some people also like having loops which count down – this can be accomplished by simply modifying the condition (and variable), and taking away one from the number each time (by either using '-=' (functions much like '+=') or '--' (functions much like '++')).
For example:

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 also 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 where you want.

One more common use of while loops, is the repetition of something until the user does something. This often uses the boolean data-type – this is a datatype which can either be set to 'true' or 'false' (see the code below).
For example, making the user enter a number between 0 and 100:

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!



For loops

There is also another kind of very useful loop called a for loop.
It's much like a while loop, however instead of having to increment a variable each time – we can easily embed this functionality inside the loop itself (which makes them 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), then we specify the code to loop in curly brackets. So something like this:

for(something;something;something)
{

}


The first part 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. It's simply the condition that must be maintained for the loop to keep looping.
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:

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 iteration 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 our for loop. You can obviously modify each section of the for 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 this 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:


This Javascript tutorial was written by


Back to Javascript

Advertisement: