JavaScript Loops: Complete Beginner Tutorial

In this beginner-focused tutorial, I will teach you everything you need to know about writing loops with JavaScript.

avatar
InstructorZach Gollwitzer
Last UpdatedMarch 29, 2024
Estimated Read Time6 minutes

What are loops in JavaScript?

I can tell you what a loop is, but my goal in this series is to also share with you why we do things. As a beginner programmer, understanding why we need loops is not going to be apparent. Sure, you might find yourself writing loops to solve some algorithm coding challenge, but in the real world of web development, there is one use case for loops that I believe trumps all.

That use case is looping over database resources.

In the "real world", we deal with a lot of repetitive things with similar characteristics. Remember how we talked about arrays earlier?

const myArray = ["orange", "blue", "green"];

The above array is simple, but in a prior lesson, we talked about how you can put more than just string values in an array. You might have an array that looks like this:

const blogPosts = [
  {
    title: "What is JavaScript?",
    author: "Zach Gollwitzer",
    publishDate: "Dec 20, 2020",
    content: "some post content here",
  },
  {
    title: "How do Arrays work?",
    author: "Zach Gollwitzer",
    publishDate: "Jan 1, 2021",
    content: "some post content here",
  },
  {
    title: "How long does it take to learn coding?",
    author: "Zach Gollwitzer",
    publishDate: "Jan 20, 2021",
    content: "some post content here",
  },
];

What do you notice in the code above? Here are a few things I'm noticing.

First, the format of the array above is much different than what we've seen before. We've looked at a lot of arrays written on a single line, but when coding, you'll often have to write code that breaks on several lines. While indentation is not necessary (if you are writing Python code it would be, but not JavaScript), it helps with readability. We will talk later in the series about auto-formatters such as Prettier to help us with this. 👍

Second, I'm noticing that each object stored in our blogPosts array has a very similar structure. Each object has a title, author, publishDate, and content property. Hmmm... We might be able to take advantage of this in a couple minutes...

When I said "resources" earlier, I'm talking about a group of similar-looking data that is generally stored in a database. A blog post would be considered an individual "resource".

So you might ask–why would we want to loop over a list of blog posts?

A good idea to remember - don't hardcode things

Let's say you are coding a blog (like we will do in this fullstack series). How would you display your blog post titles on the home page using the array we just looked at above?

Here's an idea:

blogPosts[0].title;
blogPosts[1].title;
blogPosts[2].title;

Great! All we need is a little HTML and JavaScript and we have ourselves a list of blog posts.

But what happens when we add another post?

We could just add another line of code right? Maybe blogPosts[3].title?

No. No. No. No. No.

This is where loops come in. Instead of hard coding a new line of code for each additional blog post that we add, we want to be able to have our code automatically detect a new blog post and display it.

Here's how I would display my blog posts instead.

const blogPosts = [
  {
    title: "What is JavaScript?",
    author: "Zach Gollwitzer",
    publishDate: "Dec 20, 2020",
    content: "some post content here",
  },
  {
    title: "How do Arrays work?",
    author: "Zach Gollwitzer",
    publishDate: "Jan 1, 2021",
    content: "some post content here",
  },
  {
    title: "How long does it take to learn coding?",
    author: "Zach Gollwitzer",
    publishDate: "Jan 20, 2021",
    content: "some post content here",
  },
];

// ---------------------
//   This is our loop
// ---------------------
for (let i = 0; i < blogPosts.length; i++) {
  const postTitle = blogPosts[i].title;
  const postAuthor = blogPosts[i].author;
  const postDate = blogPosts[i].publishDate;
  const postContent = blogPosts[i].content;

  // Here, we would use these variables to do something with each post
  // I'll just print the values
  console.log(postTitle);
  console.log(postAuthor);
  console.log(postDate);
  console.log(postContent);
}

No matter how many posts we add to our blogPosts array, our code is ready to display them!

The structure of a JavaScript loop

You will learn later in your programming journey that there are several valid ways to write a loop in JavaScript, but there is one way that most programmers would consider the "standard" way of writing a loop. You saw it in the code above, but here it is again.

for (let i = 0; i < 100; i++) {
  // Your code goes here
}

I know, this looks intimidating. Let's walk through each part.

Just like we start a conditional statement with the if keyword, we start our loops with the for keyword.

// The code below is not valid, but gives you a visual

if () {

}

for () {

}

Within the parentheses, we need to add the following things:

  1. A loop variable
  2. A stop condition
  3. A loop behavior

In this case, we used a loop variable of i.

let i = 0;

There are a couple things to point out. First, notice how we have a ; at the end of the statement. This indicates that our statement is complete and is required.

Also, notice that we are using let instead of const. This is intentional. The value of i will be changing on each iteration of our loop, and therefore, we need to "re-assign" it and use the let keyword to declare it.

Next, notice that we named the variable i. This is merely a convention, and is not required. We can call this variable whatever we would like. The following loop would be perfectly valid:

// Your loop variable doesn't have to be called `i`, but this is a conventional way to do it
for (let anyName = 0; anyName < 100; anyName++) {
  // Your code goes here
}

Finally, notice that we initialized this variable with a value of 0. This is important because it represents the starting value of our loop. In almost ALL cases, you will want to start your variable at 0 because when using loops, you'll be looping over an array, and when using arrays, the first value has an index of 0.

Next up, let's talk about the following code:

i < 100;

First off, the value of 100 is entirely arbitrary, and generally, you won't be using a hardcoded number like this. In most cases, you'll replace 100 with something like blogPosts.length for reasons that will become apparent soon.

Second, it is important to understand what this statement is saying. I call it a "stop condition" because the loop will continue until i reaches a value of 100.

How does i reach 100 you might ask? Well that's where i++ comes in. If you remember from the prior lesson of this series when we talked about arithmetic operators, using i++ increments the value of i by 1. Let's look at the code one more time.

for (let i = 0; i < 100; i++) {
  // This line will run 100 times and each time, i will increase by 1
  console.log("The value of i is: " + i);
}

Go ahead and open your browser dev tools (remember, right click anywhere in the browser, click "Inspect Element", and then select "Console") and paste this code in there.

Although your browser console will print 100 lines in less than a second, the computer is "iterating" through this loop and doing the following:

  1. Check if the value of i is less than 100. If so, continue to the code inside the loop.
  2. Run the code in the loop
  3. Return to step 1

Like I said, loops are not all that useful on their own, but once we start "iterating" (this is just a fancy word programmers use) over a list of blog posts, users, notifications, or whatever else you can think of, they become very useful.