Loops – Running code multiple times

JavaScript

0 Comments

Loops allow you to run the same code multiple times. They are usually used to process each item in an array.

while loops

A while loop executes the code within its curly braces as long as its conditional test is true. The code shown below uses a while loop to loop through every item in the array.

var myArray = [ 'Alice', 'Bob', 'Charlie' ];
var length = myArray.length;
// Our current index in the array
var index = 0;

// Loop through every item in the array
while (index < length) {
    var item = myArray[index];

    alert( item );

    // increment index by 1 each time we loop
    index = index + 1;
}

A walk through of the while loop code (in case it isn't clear)

You can skip this if you understand how the while loop works.

  • Before the while loop starts, we initialize length to 3 and index to 0.
  • The while loop checks if index < length (it is since 0 < 3), so the code inside the while loop executes.
  • On Line 8, we save the current item in the array. Since index = 0 at this point, myArray[index] is the same thing as myArray[0].
  • Line 13, adds 1 to our index variable to prepare for the next while loop.
  • We now loop back to the beginning of the while loop (Line 7) and check again if index < length. Index is now 1 and length is still 3, so the test passes, and we once again execute the code inside the while loop.
  • This looping continues until index is incremented to 3.
  • When we loop back to Line 7 to test if index < length, it fails this time, since both index and length are now 3. This means we do NOT execute the code inside the while loop and instead jump to the end of the loop and execute any code that comes after it.

for loops

It's very common to need to loop over the items in a list, which is what we just did with the while loop in the previous section. However, the for loop was created to make handling lists a little easier.

var myArray = [ 'Alice', 'Bob', 'Charlie' ];
var length = myArray.length;

for (var i = 0; i < length; i++) {
    var item = myArray[i];

    alert( item );
}

This code actually does the same thing as the while loop, but it's a little shorter and easier to write.

How the for loop works

On line 4, you'll notice 3 sections inside the parentheses of the for loop (each section is separated by a semi-colon).

The first section is executed before the loop runs. This is where you'll initialize your index variable (which is typically just called i instead of index).

The second section is the conditional test (works exactly the same as the while loop). If the test is true, we execute the code inside the for loop. If it's false, we skip the loop code.

The third section is where you'll put code you want run at the end of each pass of the loop. With lists, you'll usually only need to add 1 to the index variable, which is what i++ does.

How does i++ work?

i++ is a short way to write the following code:

i = i + 1;

You can use i++ anywhere in your code (not just for loops).

do while loops

do while loops are very similar to regular while loops. The difference is that the conditional test happens at the end of the loop (instead of the beginning). This means the loop will execute at least once.

Example

var myArray = [ 'Alice', 'Bob', 'Charlie' ];
var length = myArray.length;
// Our current index in the array
var index = 0;

// Loop through every item in the list
do {
    var item = myArray[index];

    alert( item );

    // increment index by 1 each time we loop
    index = index + 1;
} while (index < length);

break keyword - Breaking out of a loop early

Sometimes you'll want to break out of the loop early when some condition is met. You can do this with the break keyword as shown below.

for (var i = 0; i < length; i++) {
    var item = myArray[i];

    // Exit the loop early if item equals 'Bernard'
    if (item  == 'Bernard') {
        break;
    }

    alert( item );
}

continue keyword - Skipping some items in a loop

You'll also sometimes want to skip processing some items in a list (but not exit the loop completely). This can be done with the continue keyword.

for (var i = 0; i < length; i++) {
    var item = myArray[i];

    // If item equals 'Ashley', skip to the next list item
    if (item  == 'Ashley') {
        continue;
    }

    alert( item );
}

The continue keyword basically jumps to the end of the loop, executes i++ (if it's a for loop), and goes back to the top of the loop, so you can process the next item.

Practice Problem - Using loops to change a list of elements

Write the JavaScript code to make all paragraphs red (if they have the class red). This code should run when the button is pressed. An example of how this should work is included below along with the HTML code.

Example

HTML

<input type="button" id="myButton" value="Click me">

<p class="red">
    This should be red.
</p>

<p>
    This should NOT be red.
</p>

<p class="red">
    This should be red.
</p>

JavaScript

Open Editor

function setupButton() {
    var myButton = document.querySelector('#myButton');

    if (!myButton) {
        return;
    }

    myButton.addEventListener('click', changeColor);
}

function changeColor() {
    var redParagraphs = document.querySelectorAll('p.red');

    if (!redParagraphs) {
        return;
    }

    var length = redParagraphs.length;

    for (var i = 0; i < length; i++) {
        redParagraphs[i].style.color = 'red';
    }
}

// Run our setupButton function
setupButton();

Leave a Comment