There are a lot of ways in vanilla JS to loop over things such as an array or a NodeList. In this post we are going to look at one of the first approaches to this called a for loop.

Let's look at the anatomy of a for loop.

How the for loop works
for (initialization; condition; incrementExpression) { // Thing to do in the loop }
  • The initialization, is where you put anything that should happen before the loop runs. This is the first part of the loop before the first semicolon,
  • The condition, is a test that gets checked after each iteration of loop. As long as it’s true, the loop keeps going. If it returns false, the loop ends. This is the second part between the two semicolons.
  • Lastly, after the second semicolon, the incrementExpression, we specify what to run after each loop.

Let’s look at an example.

var pizzaToppings = [ 'cheese', 'pepperoni', 'mushrooms', 'sausage' ]; for (var i = 0; i < pizzaToppings.length; i++) { console.log(i); // index console.log(pizzaToppings[i]); // value } // returns 0, "cheese", 1, "pepperoni", 2, "mushrooms", 3, "sausage"

For our initialization, we’re setting up a counter variable. After each loop, we’ll increase this by one, and use it to know which item in our array we’re currently looking at in the loop.

In the condition, we’ll make sure that our counter variable is smaller than the total number of items in our array. If it’s not, we’ve looped through the whole array and can end the loop.

Finally, in our incrementExpression, which runs after each iteration of the loop, we’ll add 1 to our counter variable (i).

Inside the loop, we can use the i variable to get the current item in the loop from our array, like this.

pizzaToppings[i];