Loops

A loop is a construct which lets us execute the same code multiple times with slightly different parameters each time.

There are two main types of loops.

While Loop

These loops will run until a condition is no longer met. Be careful with this, as they can run forever!

var count = 0;
while(count < 10) {
    console.log(count);
    count = count + 1;
}

For Loops

These loops will run a set number of times, according to the counter declared in the statement

for (var i = 0; i < 10; i = i + 1) {
    console.log(i);
}

🤔 What is happening here?

The statement (the bit in between the brackets) has 3 parts. those parts are separated by the semi colons ;. The first part sets up the counter for the loop, the second part defines the condition for the loop to execute until, and the third part is responsible for iterating the counter at the end of each iteration.

We can use this to iterate through an array, too. for example:

var animals = ['Cats', 'Dogs', 'Geese'];

for(var i = 0; i < animals.length; i++) {
    var animal = animals[i];
    if (animal === 'Geese') {
        console.log('I do not love ' + animal);
    } else {
        console.log('I love ' + animal)
    }
}

Last updated