Ahh, the for loop. A highly important tool for the programmer.
I've been learning JavaScript for the past eight months and I have really come to enjoy using for loops.
The first time I used a for loop to create multiple DOM elements at once, I felt like a wizard and a genius 😎. Call me "Gandalf", bruh, 'cause I'm out here castin' spells.
Looping through arrays of data and creating multiple dynamic elements in the DOM are just a couple of ways I have used "for loops" since I began my coding journey.
There are many different variations of the for loop - "for...of", "for...in", "forEach". But today, we'll just focus on the regular ol' for loop.
What Even Is a For Loop, Though?
Stealing this simple definition from MDN Web Docs, "Loops offer a quick and easy way to do something repeatedly."
It's that simple. Though, if you're brand new to programming, that definition may not suffice without adding a bit of context.
So, let's first explore the structure of the for loop and break it down piece by piece.
For Loop Structure
for (let i = 0; i < 10; i++) {
console.log(i);
}
This ^ is a for loop. Let's dive into what the hell is going on here.
We'll quickly break down what's happening in this simple for loop then further explore each individual section.
We are simply:
- Declare a counter to begin at 0.
- Write a condition to stop the loop (the loop stops before reaching 10).
- Running a block of code for each iteration (console.log(i), in this case).
- Increment the counter after the code block runs (move from 0 to 1).
Let's break it down step-by-step:
Setting Counter to "0"
let i = 0;
The loop allows us to iterate through a set number of values. Therefore, it's common practice to use "i" as our variable name - "i" for "iteration" - get it?! Pretty intuitive, yah?
Also, we utilize a "let" variable, rather than "const", because the value of the of "i" will be reassigned each time we iterate through the loop. As you may already know, the value of a "let" variable can change, while the value of a "const" variable cannot.
That said, within the first part of the loop, we set the value of our variable "i", to "0". In programming, we generally begin counting from "0" rather than "1", though you can set this value to anything you like.
So let i = 0
is now our starting variable.
So far, so good. Onto the next section.
Declare an Action Within Our Code Block
{
console.log(i);
}
We have created a code block with our curly braces {}.
Anything within this code block will run at the beginning of the for loop and again each time we iterate to the next value.
For this particular code block, we are simply logging the current value of "i" to our console.
Therefore, when "i = 0", our code block will log the value of "i" to the console. Meaning "0" will be logged to the console.
Set a Condition to Stop Loop - You Don't Wanna Overdo It
i < 10;
Remember grade school math? i < 10
means the value of 'i' will never make it to '10'. If we did i <= 10
, our count will make it to '10' because we included '10' by using our "=" sign. "i is less than, or equal to, '10'."
For the purposes of this tutorial, however, "i" is less than 10.
This part of the for loop sets the maximum value that we'll be aiming to reach.
Think of this as our for loop's "limit". If we don't set a limit, this will result in what's known as an "infinite loop". An infinite loop will increment indefinitely and thereby crash our program.
The loop would run "to infinity and beyond!" Great for space exploration, not so great for the programmer.
Increment after Code Block Execution
i++
Huh?
This part of the for loop allows the actual counting to take place. It says "Once I run your code block for 'let i = 0', I'm going to bump your variable up to 'let i = 1' and run the code block all over again."
It's dope like that. We just sit back and watch the magic take place.
Okay, So What Are the Results?
for (let i = 0; i < 10; i++){
console.log(i)
}
This results in the following output to our console:
0
1
2
3
4
5
6
7
8
9
Nice! We set parameters for our for loop and printed some results in the matter of milliseconds! Pretty cool.
If our for loop were a human, he might say: "Well i = 0, so I better use that to complete the action in the code block. Ah, looks like we're going to log the value of "i" to the console. Okay, I logged that, what's next? Ah, we're incrementing to let i = 1? Okay, looks like 1 needs to be logged to the console..." and so on, until we reach the maximum we set for the for loop - in this case, "9".
Implications of the For Loop
We counted 10 values. Fantastic. Okay, what else can we do with a for loop? There are many use cases, which I won't fully explore in this quick introduction.
But let's just say we need 30 different HTML divs, for example.
Yes, I could painstakingly type out 30 different divs in my HTML. But this ain't the 1500s, and I'm not an ancient monk working by candlelight. I'm way too lazy to do something like that.
Instead, we use a for loop and instantly create 30 divs at the drop of a hat.
Example:
// Grab the main div container from the DOM
const mainContainer = document.querySelector("#main-container");
/*
Loop through numbers 0 -> 29 (remember, less than 30 so 30 doesn't get counted)
*/
for (let i = 0; i < 30; i++) {
const innerDiv = document.createElement("div");
innerDiv.classList.add("inner-div");
// Append new innerDivs to the mainContainer
mainContainer.appendChild(innerDiv);
}
I won't go into details of appending the DOM in this blog post - just know that I dynamically created 30 different divs in the DOM using this little block of code. Pretty sweet, huh?
Wrapping Up
In closing, learning the for loop seemed so difficult to me mere months ago. Now, I use it constantly.
In future blog posts, I plan on delving into the many different loops variations. After all, loops serve as a major foundation of programming.
For now, just know that they are simpler than they appear at first glance and are quite useful.
/Sam's Dev Lab
Top comments (2)
Code blocks can be formatted in Dev.to as follows:
triplebacktick javascript
code
triplebacktick
Also please indent your code.
Just now seeing this - I appreciate the feedback and the tips. Fixed!