JavaScript Basics Part 7: Loops

Loops are used to execute the same statement of code a set number of times, which can be hardcoded or based on variable.

Loops are very common within programming, as they solve the problem of having to write more code to do the same thing multiple times. There are two different types of loops: for and while loops, which both perform looping tasks but in different ways, suitable for different problems.

for

The for loop will run for a set number of times then stop.

var I = 0;

for(I = 0; I < 5; i++) {
	Alert("My number"+ I);
}

If you had to write out a sentence five times, you could do it by writing out each statement. The code can become repetitive and will get hard to manage as you add more lines. Imagine it was 20 sentences, or even 100 sentences – just think of all the code you would have to write.

document.write('The next number after 1 <br>');
document.write('The next number after 2 <br>');
document.write('The next number after 3 <br>');
document.write('The next number after 4 <br>');
document.write('The next number after 5 <br>');

You can write the same code as above in a loop, which will be much easier to scale and manage as you need to add more items to the loop.

var numCount = 0;
for (numCount = 0; numCount < 20; numCount++) {
    document.write('The next number is' + numCount + '<br>');
}

In the proceeding example, I have achieved the same result as writing it out by hand, but only using 3 lines instead of 5.

I’m going to break down each step, so that you will understand how to write your own for lo