learntheweb

For Loops

Introduction

Now that we have learned about the while loop, it’s time to explore another powerful looping construct in Javascript: the for loop. While the while loop is useful when we don’t know how many times we need to iterate, the for loop is great when we do know the number of iterations in advance. Let’s get started!

Overview

By the end of this lesson, you should be able to:
    • Understand what for loops are and how they work
    • Understand the syntax of for loops in Javascript
    • Understand how to iterate through lists with the for loop
    • Understand output and syntax of for loops

For Loops

The first part of understanding for loops is to understand the three different parts of making a for loop. They are the initialization, condition, and increment. Take a look:

Let’s go through each part step by step. 

    1. Initialization: This is where you declare the variable(s) you will use in the loop and initialize them to their starting values. For example, let counter = 0 initializes a variable counter to 0.

    2. Condition: This is where you specify the condition that must be true for the loop to continue running. For example, counter < 10 specifies that the loop should continue running as long as counter is less than 10.

    3. Update: This is where you update the variable(s) used in the loop after each iteration. For example, counter++ increments the value of counter by 1 after each iteration of the loop.

With all of that said and done, let’s write some simple code to print out all the numbers between 1 and 10 using a for loop. Here is how we do it:

for (let number = 0; number <= 10; number++) {
    console.log(number)
}

The great thing about for loops is that we don’t need to declare a variable in a new line; we can just declare our variable within the loop itself. In this example, we are declaring the variable number within the for loop itself. We are then looping through the loop until number reaches 10.

 

What if we wanted to increment number by 2 instead of 1? Take a look:

for (let number = 0; number <= 10; number += 2) {
    console.log(number)
}

Let’s look at some more use cases of for loops by using them to iterate through lists!

Iterating through Lists

Just like with while loops, for loops also allow us to iterate through lists easily. Here is how we do it:

let foods = ["pizza", "cake", "pasta", "cookie", "curry"]

for (let i = 0; i < foods.length; i++) {
 // Logging the list-item at each index in the list "foods"
    console.log(foods[i])
}

In this example, we are using a for loop to iterate through every item in a list and print it out. 

 

The first thing to notice is our condition. We are setting our variable i to iterate until it is smaller than foods.length. This allows us to iterate through the loop until we reach the end of it (hence, why we took the length of our list).

 

After that, we make sure to increment i by 1, and print out each item of our for loop. One of the biggest mistakes made by beginners when looping through lists is setting the condition to i <= foods.length. The problem with this is that it will loop one extra time on our list. Go ahead and run the following code in your code editor. Notice what happens:

let foods = ["pizza", "cake", "pasta", "cookie", "curry"]

for (let i = 0; i <= foods.length; i++) {
 // Logging the list-item at each index in the list "foods"
    console.log(foods[i])
}

Our last value is going to be logged as undefined since we are trying to log an index that does not exist. When our variable declaration is 0, our conditional should always be i < list.length.

The For Of loop

Another way we can loop through every item in a list is to use the for (of) loop that we have here in Javascript. It’s a very simple one to use and understand and an alternate to the traditional for loop. Here is how we use it:

// Declaring our list
let foods = ["pizza", "cake", "pasta", "cookie", "curry"]

// For Of loop
for (let item of foods) {
  console.log(item) // Logging each item of the list "foods"
}

// Put this in your code and see what it logs out!

As you can see, using the for of loop can be used to quickly loop through an array. In the above example, we are declaring our variable item within our for loop condition, and then then logging each item to the console. Let’s look at one more example:

let numlist = [1, 2, 3, 4, 5];

for (let number of numlist) {
  console.log(number * 2);
}

// Output:
// 2
// 4
// 6
// 8
// 10

In this example, we are looping through our list numlist, and multiplying every number by 2 and then logging that. Notice how we declare the variable inside our condition just like with a regular for loop!

Practice

Now that you have a good grasp on the fundamentals of the for loop, let’s do some practice with them! Here are three exercises to test your skills. Each exercises provides some starting code and a hint in case you are stuck. If you are still stuck on an exercise, feel free to join our discord server for futher contact/help.

Problem #1

Write a JavaScript program that sums up the contents of a predefined list called numList. Here is the starting code for this problem:

let numList = [2, 4, 6, 8, 10];
let sum = 0

for (some condition) {
    // Write your code here
}

console.log(sum) // Should log "30" (2 + 4 + 6 + 8 + 10)

Let’s take a second and think about this. We know that in order to accomplish our problem, we will need to iterate through each item in the list, and add it to sum. You can use a for loop to iterate over the elements of the numList array and add each element to a sum variable.

Problem #2

Write a JavaScript program that finds the largest number in a predefined list called numList. Here is the starting code for this problem:

let numList = [3, 7, 2, 9, 1, 5]
let largestNum = 0; // This will be changed by your code

for (some condition) {
    // Write your code here
}

console.log(largestNum) // Should log "9"

Let’s think about this problem for a moment. The goal is to find the largest number. What we can do is loop through our list numList and whenever we find a number larger than largestNum, we will set largestNum to our number. This will require an if loop inside of our for loop. Try to give it a shot!

Problem #3

Write a JavaScript program that finds the sum of all the even numbers in a predefined list called numList. Here is the starting code for this problem:

let numlist = [12, 13, 21, 4, 8, 9, 0]
let evenSum = 0; // This will be changed by your code

for (some condition) {
    // Write your code here
}

console.log(evenSum) // Should log "24" (12 + 4 + 8 + 0)

This is similar to what we did in the first problem. You can use an if statement to check if each element is even, and if it is, add it to our variable evenSum