Introduction to Loops in JavaScript

Today we are going to talk loops in programming.

Loops, what are they and why do we use them?

In programming we use loops to repeat blocks of logic or code. Now that sounds like kind of a boring definition for something that we use so often in web and software development. I would go as far as to say that understanding how loops work in programming is a FUNDAMENTAL SKILL. In JavaScript we have more than one way, in fact we have several, of using loops to perform a function or operation. But we all need to start somewhere, and in case you are just starting out on your development journey then we should get started at the beginning.

The first loop we tend to learn in any programming language, in our case JavaScript, is the trusty for() { ... } loop.

for ( ) loop syntax:

for (initialExpression; testingCondition; updateExpression) {
    // body or scope of "for" loop
}

What is happening here? Let's explore what is going on when we execute a for loop.

  • We initialize or declare a variable to use as an iterator and initialize it to a starting value. It is pretty common in programming to use i = 0. It is important to note that this part of the for loop is only executed once, the first time through loop execution.

  • The testingCondition is evaluated and tested at every iteration through the loop. You can kind of think of the testing condition as the gate keeper of the loop. If the condition (i < 10) evaluates to true, the block of code inside of the for loop is executed. If the condition evaluates to false, the loop execution is terminated (or never evaluated if the initial test condition never evaluates to true) and we continue on with the code after the loop.

  • The updateExpression updates the value of the iterator variable when the condition is true. Updating the iterator value can be more than simply increasing or decreasing by one. We could skip values and look at only the even or odd values by updating the iterator variable using something like i+2. Try it out!

  • The testingCondition is evaluated again and this process continues until the condition evaluates to false and we continue on with the code after the loop.

That is a lot of explanation! Sometimes a good visual is helpful in wrapping our heads around these ideas, especially when they are new to us.

for-loop-js

Let's take a look at a simple example using a for loop to count from 0 to 10:

// count up from zero to ten
for (let i = 0 ; i <= 10 ; i+1) {
   console.log("value of i is " + i);
}

console.log("I am code after the loop");

// output -> value of i is 0
//           value of i is 1
//           value of i is 2
//           value of i is 3
//           value of i is 4
//           value of i is 5
//           value of i is 6
//           value of i is 7
//           value of i is 8
//           value of i is 9
//           value of i is 10
//           I am code after the loop

We could also reverse the direction that the loop counts or moves by modifying the setup of our loop. Let's take a look at how the for loop would be formed if we wanted to count down instead of up.

// count down from ten to zero
for (let i = 10 ; i >= 0 ; i-1) {
   console.log("value of i is " + i);
}

// output -> value of i is 10
//           value of i is 9
//           value of i is 8
//           value of i is 7
//           value of i is 6
//           value of i is 5
//           value of i is 4
//           value of i is 3
//           value of i is 2
//           value of i is 1
//           value of i is 0

Take notice, what did we change and how did that effect how the loop operated? Well instead of initializing the starting value of the iterator variable to zero we set it at the value that we want to start with. Next, how did we change the testing condition? Had we only updated the starting initial expression then all we would have done is start counting up from ten. The testing condition is updated so that as long as the iterator value is greater than zero we continue on to running the logic inside the loop. Lastly we check the update expression for the loop's iterator. Since we want to count down from ten (initial expression) to zero (testing condition expression) we will need to subtract one after each successful iteration through the loop. Play with the starting values in the loop and count up to 100 or 1000, play with the testing condition to see how you can limit the number of times the loop is executed. Play with the update expression and see how that changes the loops operation.

So, all we do with loops is count?

It would not be useful if you could only use a for() loop to count up or down would it? Understanding the basics of how they operate and how to change the code to perform the operation you want to run is very important because of what loops, for() and others, allow us to do with traversing or looking through data that we are interested in showing to the User, updating, or modifying data etc. This is where the real power of loops comes into play. In a similar way in which we were just counting up from zero to ten, we could inspect each element in an Array. Or what if we wanted to inspect the Array data starting from the end of the Array and not the beginning? We would setup our for loop in a similar way where we counted down from ten to zero.

We will take a look at how we loop through data in Arrays and Objects with JavaScript in future articles, so stay tuned!

Infinite Loops:

What happens if we accidentally end up writing a testing condition that never evaluates to false? Well we end up in a condition we refer to as an infinite loop, where as the name states we continue to run the code within the loop forever ... and ever ... FOREVER!!! bwmmmuhaaahahah!!!

bowser.png

Too much? Yeah... Anyway, if we never exit the loop then the rest of our code cannot run and then the whole application stops execution. Not exactly the user experience we want to provide to our clients, so this is an important part of always testing our code to make sure we don't run into any surprises like an infinite loop situation.

Continue Learning:

There are more uses and looping methodologies than we covered in this article. We just started down the path of understanding what loops are and how we might use them in our own code. Plus we will talk about them in future articles.

More loop types and uses:

  • while() loop
  • do/while() loop
  • forEach() loop
  • Higher order functions such as map(), filter() and reduce()
  • loop through items in an Array
  • loop through items in an Object

Hopefully this article on loops in JavaScript was useful to you. Thanks for reading, until next time!