JavaScript loops and iterating through them

Michael Abe
3 min readOct 21, 2021

Recently when working through a few coding challenges, I realized that sometimes sometimes when things progress, we as evolving people can sometimes lose sight of the fundamentals that we build upon for more complex procedures. I was thinking about this concept while working out efficiency of code. One of the most basic and fundamental elements that we use for coding is looping and iterating. As vital part of coding, let’s revisit and refresh our familiarity with basic level of loops.

As most people that have done much in the coding world at all know, we often need to do the same thing multiple times. Writing the code to be run independently every time that we needed it to be run would be a huge mess, besides the massive amount of physical space that the code would take up in our editors, when we have repetition of code our likelihood and potential to make an error increase. Ultimately, repeating code is just ineffective and not recommended and often in programming we need to repeat an action a certain number of times…enter loops.

The most basic and probably used built in function that we have at our disposal in JavaScript is the For loop. The for loop repeats until the condition that you specify is no longer true. The basic for loop counter could be written as

The first line is declaring ‘number’ as a variable. In this case we are setting the number to be zero. The second part of the for loop is the condition that we are saying we want to evaluate. In this case we are saying that as long as ‘number’ is less than 5, we want to keep running our for loop. This will be evaluated and unless ‘false’ is returned, the loop will continue. The third part of line one is an increment that we want to enact on out counter ‘number’. In the case above, we are adding one to ‘number’ each time that the function is run. As we can see in the console on the right of the function shows that our counter ran every time that ‘number’ was less than five.

This is just a basic counter example but as you can see we utilized the for loop to prevent us from writing repetitive code. In order to get the same results we would have to write:

While this may not look that bad, we have to keep in mind that this is a tiny example. If we wanted to count up to 1,000 we would have to write the same ‘console.log()’ line out 1,001 times (since we started at 0)…alternatively that code using a for loop would look basically identical to the first example that we used aside from changing the ‘number < 5’ section to ‘number < 1001’…as you can see, the for loop is much faster to write, more concise, and essentially objectively better code.

--

--