Relearning the for Loop

One of the strange things that happens as you expand your coding toolset is that you often learn some of the more challenging concepts first, only to discover easier ways to accomplish the same feats later on. Ultimately, this is a good thing, because you don’t just want to learn what works, but also why things work. However, this can create a situation where old, useful knowledge begins to slip away in favor of more efficient means of working.

This has cropped up for me lately whenever I want to iterate over an array. I’ll often use built in JavaScript methods like .map() or .filter() to achieve my intended result. I’ve noticed that this has slowly replaced some of the early techniques I used for looping — techniques I am not eager to forget as they can be incredibly useful in certain circumstances.

Today, I want to break down the granddaddy of all loops: the for loop, to better understand how it works and why it can be useful.

A for loop is probably the simplest iterative statement. It allows you to repeat an action multiple times. For example, if you wanted to log the phrase, “We will, we will rock you!” five times, you could write the following:

for (let i = 0; i < 5; i++){
console.log("We will, we will rock you!")
}
// => "We will, we will rock you!"
"We will, we will rock you!"
"We will, we will rock you!"
"We will, we will rock you!"
"We will, we will rock you!"

How does this work?

Fundamentally, the best way to think about a for loop is that it will continue to run your code over and over until specific condition — that you set — is met. If there was no condition, the loop would run forever: it would become an endless loop, which is something we desperately want to avoid because it can result in a whole host of problems.

So let’s breakdown our code:

First, we want to declare our for loop by creating a simple function.

Next, we need to initialize a counter, providing the value we want our counter to start with. Typically, this would be 0, as is reflected in our code (let i=0), but not always. This initializing value can be as complex as you need it to be and you can even declare variables in this section of the loop. But for our purposes — and most purposes really — 0 will do.

Once we’ve initialized our counter, we need a conditional expression. This is where we’ll set the condition for the loop to end. Our loop will continue to run for as long as the condition returns true. As soon as it is false, the loop stops. In our example, our action repeats as long as our i value — assigned as our counter — remains less than five (i < 5). Generally, you’ll want to use an operator that will allow you to compare your counter to another value.

Finally, we want to increment our counter with each loop (i++). On the first loop, our counter will return a value of 0. But because of our incrementor, on the second loop, our counter will return a value of 1. This will continue until we hit a value of 5, at which point the conditional will return false and the loop will stop. You can see why the incrementor is essential to our loop structure.

Once we’ve laid out our counter, our condition and our incrementor, we can place the code we wish to repeat into the body of the function, between two curly braces: {}.

Now let’s use a for loop to solve a more complicated problem.

Let’s say we want to retrieve the highest number from an array.

let array = [100, 87, 12, 150, 750, 45, 0, 920]

How would we do this? Let’s think about what we need:

  • To iterate over every element in array and stop looping once we’ve reached the final element.
  • To compare each number with the largest number that has already been looped over.
  • If the number is higher than the largest number, replace it as the highest.
  • Return a console log of the largest number once the loop is complete.

I’m going to show you my solution and then we can walk through it step by step.

let largest = 0for (let i = 0; i < array.length; i++){
if(array[i] > largest){
largest = array[i]
}
}
console.log(largest)

Before, I start my for loop, I set a variable called largest to a value of 0. Why is that? Because if I am going to compare every element of the array to an initial variable, I want to start with the lowest possible value so there is something to replace. Every value in my array is going to be equal to or greater than zero, so it won’t cause any issues while looping through and comparing the elements of the array.

After declaring my for loop, I initialize my counter at 0. I also create my conditional expression, stating that I want the loop to continue for as long as the counter is less than the length of the array. Once we’ve hit the last element of the array, I want the loop to stop because there’s no work left to do. Finally, I increment my counter. The ++ operator will update it by one for each loop.

In the body of my function, I place the code that I’m going to use to determine the largest value in my array. If the value of array[i] — or the current value — is greater than the value of largest, then that value will be set as the new largest value.

Once the loop is finished, I console log the value of largest, which should be the highest number in the array. I do this outside of my loop because I only want it to run once the loop is complete, not every time it iterates through the array.

To really hammer this home, let’s look at this every step of the way:

  1. On the first loop, our counter is set to 0. Since 100 is greater than the value of largest (0), it is replaced. The new largest number is 100.
  2. On the second loop, our counter is set to 1. Since 87 is less than 100, nothing happens.
  3. On the third loop, our counter is set to 2. Since 12 is less than 100, nothing happens.
  4. On the fourth loop, our counter is set to 3. Since 150 is greater than 100, 150 is our new largest.
  5. On the fifth loop, our counter is set to 4. Since 750 is greater than 150, 750 is our new largest.
  6. On the sixth loop, our counter is set to 5. Since 45 is less than 750, nothing happens.
  7. On the seventh loop, our counter is set to 6. Since 0 is less than 750, nothing happens.
  8. On the eighth loop, our counter is set to 7. Since 920 is greater than 750, 920 is set to largest. Since array.length is 7, the loop stops running.
  9. We console log the highest number: 920!

We’ve done exactly what we set out to do with a for loop and a little bit of extra code. What’s more, this should work with any array of positive numbers, regardless of what they are or how many there are.

For loops are not the trendiest or the most efficient option when it comes to array iteration, but they are one of the basic building blocks of JavaScript. They are an essential part of our toolkit and it’s important to keep them in mind, even if map, filter or select will get use much more often.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store