DEV Community

Cover image for JavaScript 'for loops' for Newbies
Lindsey Fonnesbeck
Lindsey Fonnesbeck

Posted on • Updated on

JavaScript 'for loops' for Newbies

When I first started to learn how to code, I remember the concept of loops having me stumped for what felt like the longest time. No matter how many videos I watched and materials that I read, I couldn't get the concept to click in my mind. My biggest frustration was that it felt like no one remembered what it was like to be a beginner and not know anything about code, all the explanations used technical terms that made it feel more confusing than it really was. I vowed that one day I would write my own explanation on loops, that explains loops the way that I wish they were explained to me!

The purpose of a for loop is when you want to repeat an action multiple times.

Without using a loop, if you wanted to console.log a phrase 10 times you could do it like so:

Code snippet

Whew! That definitely takes up a lot of space, and could be made a lot easier. What if we had to do that 100, or 1000 times?? Or what if we were wanting to console.log each value in an array (a list of values) with a lot of values in it?

In comes the power of the loop!
A for loop consists of 3 parts: the initial expression, the condition expression, and the increment expression.

All for loops will start the same way.

code snippet

Don't panic! These are the technical terms that I mentioned had me feeling flustered when I was trying to learn.
The initial expression is the count that you want your loop to start at. Usually this is 0, but you can start it at any number you want. You will declare the value that you are starting at as a variable, in this case you will use 'let' instead of 'const' because the value will be changing each time the loop runs.

A common variable name used for the initial expression is 'i'. This typically stands for index (as in the index value of an array) but you can name it whatever you want as long as you keep using that same variable name that you assigned the initial expression to. Again, 'i' is just the name of the variable, it doesn't do anything special other than name the variable so that we can keep using it.

code snippet

One way that I liked to do was refer to 'i' as the loop itself. So if we assign let i = 0, in my mind I knew that meant the loop itself is starting at 0.

Next we have the condition expression. All this means is; how many times do you want the loop to run? If we want our loop to run 10 times (aka our action to happen 10 times), we just say it like this:

code snippet

By saying that we want the loop to run while 'i' is less than 10, this will have our loop run until it reaches 10 since the value starts at 0 and increases each time the loop performs it's action. This is where you need to be careful to not create an infinite loop on accident!

If we were to write it like this:

code snippet

We would have big problems here! Our loop starts at the count of 0, and then we are telling the loop that we want it to run while the loop's count is greater than 10. Once our loop runs 10 times, it will keep running because it will always be greater than 10 after that point. This can cause your browser to crash from running the loop for so long, but everyone has to create an accidental infinite loop at least once to remember why to double check how many times we are really looping.

Next we have our increment expression. Remember how I said our 'i' variable will increase each time that the loop runs? The increment expression is what causes 'i' to increase. A lot of the time, we will increase it's value by 1 each time that the loop runs, but you can increase it's value by whatever you want. Or even decrease it if you are starting 'i' at a value larger than 0.
So now all put together we have:

code snippet

If you aren't familiar with the ++ operator, it adds 1 to our value and then returns the previous value of 'i' + 1.

Now that we have our loop constructed, we just have to do something with it! Remember the curly braces, and insert inside whatever you want to happen for the duration of your loop.

code snippet

console

As you can see here, we have our phrase printing to us 10 times, and we are also printing the value of 'i' so that you can visually see that 'i' is increasing in value each time that our loop runs

I mentioned previously that another use of for loops is to loop through an array's values. To do so, all we would need to do is reference the array's length property instead of hardcoding the condition expression to a specific number. We would then be able to use 'i' as the index value, so that each index in our array is utilized.

code snippet

console

When applying these concepts to a real scenario, you likely won't just be printing out values to the console. But now you can take these same concepts of creating a for loop and apply them if you need a function to run a certain amount of times, or if you need access to the index value in your loop.

Let me know how you decide to implement a for loop in your project!

Discussion (6)

Collapse
lukeshiru profile image
LUKESHIRU

Nice! It might be worth mentioning that when working with arrays (like the sailors array, loved that reference btw), you can use for..of instead:

for (const sailor of sailors) {
    console.log(sailor);
}
Enter fullscreen mode Exit fullscreen mode

Or even better, arrays already include methods to loop over them, so you could just:

sailors.forEach(sailor => console.log(sailor));
// or
sailors.map(sailor => console.log(sailor));
Enter fullscreen mode Exit fullscreen mode

It's been a few years since I last used for in real world scenarios in JS, but still for folks coming from languages without methods for arrays like map or forEach, for might be the best to get started with looping.

Cheers!

Collapse
ptejada profile image
Pablo Tejada

Just by title of this article I knew what I wanted to leave a comment about and since echoed my you are getting my reply ๐Ÿ˜Ž

Ironically the for loop is probably one of the most common loops thought in tutorials and getting starting guides but in practice is one of the less used loops.

Collapse
lindsfonnes profile image
Lindsey Fonnesbeck Author • Edited on

Hey, thanks for your input! ๐Ÿ˜Š
I agree that those methods are more commonly used, but felt they'd be suited for a separate article. I'll be sure to link it in this article when I have it written.

Collapse
jonrandy profile image
Jon Randy • Edited on

It's worth pointing out that the expressions can be omitted. For example, you could make a for loop run for 5 seconds, then end:

const startTime = performance.now()
for (;performance.now()-startTime < 5000;) {
  console.log('Running for 5 seconds')
}
Enter fullscreen mode Exit fullscreen mode

Or, run until some external process is complete:

for (;isExternalProcessComplete();) {
  console.log("Process is still running...")
}
Enter fullscreen mode Exit fullscreen mode

Or, run forever (probably not advisable):

for (;;) console.log("Don't do this")
Enter fullscreen mode Exit fullscreen mode
Collapse
jonrandy profile image
Jon Randy

It is also possible to omit the statement(s) to run, and do all processing purely in the expressions. If you do this however, you must follow the closing bracket of the loop conditions with a semicolon (one of the few cases in JS where the semicolon is mandatory)

Collapse
lindsfonnes profile image
Lindsey Fonnesbeck Author

Interesting, thanks for that! Learning something new every day!