Understanding the Difference Between For Loop and ForEach in JavaScript

An illustrative guide on when and how to use the for loop and the forEach method in JavaScript.

Introduction

When programmers want a portion of their code to execute a set of actions repeatedly, most times, till a certain condition is fulfilled, they save their time and energy by using loops. The crude alternative is writing the same set of code in the amount of time needed for the code to run such a task. Hence, you could either write a code once and tell it to run a thousand times or write that one block of code a thousand times. For example, suppose you were given a task to write the following statement one hundred times “Svelte is sweeter than React”, As someone who has never heard of programming or loop, how would you write it? By the end of this article, if you have yet to carry out that assignment, you’ll be equipped with the magic necessary to do so.

Prerequisite

While a basic understanding of JavaScript is a must-have to get the most out of this guide, it is helpful but not necessary to be familiar with HTML and CSS.

The Concept of Loop in JavaScript:

Repetitive/iterative tasks are common in programming and loops are a good way of writing less code to execute such tasks and avoiding syntactical errors. In the JavaScript language, there are various ways to execute iterative tasks and while most of these iteration techniques seek to implement an action: perform repeated tasks programmatically, there are some distinct differences and use cases among these iteration techniques.

These are some of the loop systems in JavaScript:

  1. For in loop

  2. For of loop

  3. While loop

  4. Do while loop

  5. For loop

This article highlights two looping techniques in JavaScript (for loop and forEach), their differences, and their use cases.

The For Loop

The for loop executes an action for a specified number of times or until a certain condition is fulfilled. Take for instance our task of writing “Svelte is sweeter than React” a hundred times, can you tell the specified number of times it should be written? Correct, 100. We can then say that the only condition you should stop writing is when the number of times it is written equals 100. This condition helps to know when to stop or even start the looping process. The genius of the for loop to understand why it should iterate and when to stop the iteration will be explained below.

Syntax

Primarily, this is the basic syntax of the for loop:

for (initialization; condition; increment) {
           // code to be executed
}

Initialization is the starting point of the loop, where you initialize a loop control variable or set some initial conditions.

Condition is a boolean expression that determines whether the loop should continue running or stop. If the condition evaluates to true, the loop code will be executed. If the condition evaluates to false, the loop terminates.

The Increment is the operation that updates the loop control variable on each iteration. It is usually used to modify the loop counter in a way that brings it closer to the termination condition. The increment is executed after each iteration of the loop, just before checking the condition for the next iteration.

To understand what goes on behind the scenes, we will run our task using the for loop and get a clearer understanding of the mechanism of the for loop. To print “svelte is sweeter than react” a hundred times, let us pinpoint the basic expressions in the task.

// Task: Write a program that prints "svelte is sweeter than react" a 100 times.

In plain English, we should not stop writing the statement until we have done so a hundred times; this interpretation spells out the condition which is a requirement in the basic syntax of the for loop as mentioned above. When we fail to identify a condition, it is the same as being told to repeat the task to infinity. Hence, the word “Infinite Loop”. An Infinite Loop is a loop that continues to run indefinitely without ever terminating. This is bad for our program as it could consume space and crash our browser.

Since we have identified our condition and we know we are to start from one (initialization), let us go ahead and write our code:

for (let i = 0; i < 100; i++) {
    console.log("svelte is sweeter than react");
}
// this will print out "svelte is sweeter than react" 100 times

Let’s do a quick breakdown of the program above:

let i = 0;

This statement, referred to as initialization, is a declaration that serves as a starting point for our program. It provides a counter to identify where we currently are or how many times our code has run. For the sake of coherence, we will ignore the condition but skip to the increment syntax for now.

i++; // it could also be in the negative, that is `i--;` as may be needed

This statement increments the counter variable we declared above. It is responsible for taking us from where we are to where we want to end, in this case, a hundred (100).

i < 100;

This is the condition that determines whether our block of code should keep running or stop. It evaluates if our condition is true or false, and based on the result of the evaluation, it determines if the code block should run.

Bringing all these together, our code first initializes our counter, and checks if the value of our counter is less than a hundred, which is our condition. The result of this can either be true or false. If it’s true, that means the counter is less than 100 and the code block should be carried out; then we increment the counter.

Let us imagine that we just printed the 69th “svelte is sweeter than react”, the counter value is incremented from 69 to 70. Then the condition checks if 70 is less than 100, if it is, the code block runs again and the value is incremented to 71, and so on till it reaches 100. At this stage, the counter, 100, when evaluated by the condition is not less than 100, hence, the code block will not run and the loop will be exited.

While there are some relational concepts to the for loop, for example, concepts like break and continue, our focus is primarily on the basics of the for loop and forEach method and how they compare and contrast with each other.

The forEach Method

The forEach is a method used to iterate also, however, it is used on arrays to run an action on each of the elements in the given array. It can be written in plain English as: “For each of the elements inside this given array, do this”. The “do this” part of the statement above is usually a function (callback function, that is, a function that is called to execution by another function) that contains what should be done on each element inside the given array.

The forEach is called a method because methods are blocks of code (functions) associated with objects and they are used to perform specific actions. Hence, the forEach method does not operate independently but it is used to perform operations on given objects (arrays). This presupposes the existence of an array in which we need to execute an action on each of the elements in that array.

Syntax

array.forEach(function(currentValue, index, arr)) //arr and index are optional
// arrow function
array.forEach((currentValue, index) => {
    //do something
})

The syntax above assumes that array exists and contains some elements which need certain actions to be performed on them individually. The code function(currentValue, index, arr) is a function that runs on each of the elements in the array. This is usually called a callback function because it is a function and also an argument of a function called by the forEach method.

In the function(currentValue, index, arr):

  • currentValue - the current element of the given array

  • index (optional) - the index of the current element

  • arr (optional) - the array of the current elements, that is, the given array

As earlier mentioned, forEach presupposes the existence of an array that needs some actions to be performed on each element of the given array. We will explore this array method with code examples.

// Task: find the square of the elements of a given array of numbers
const given_numbers = [1, 2, 3, 4, 5];

// the formula will be the particular number times itself.
// hence, where 4 is given, the square will be 4 * 4

// Using forEach to square each element (callback function)
given_numbers.forEach((number, index, array) => {
  array[index] = number * number;
});

// This will be the result below:
// [1,4,9,16,25]

Let us explore another example using strings this time. Suppose we have an array of names of persons who are presidents and we want to programmatically add 'president' to their name, how do we do this?

let names = ['Buhari', 'Trump', 'Tinubu', 'Biden', 'Obasanjo', 'Obama'];

// using forEach, we can add 'President' to the names
// Let us first declare our function:
function bePresidential(currentValue, index, array) {
    // then let's add president to the array elements
    array[index] = 'President ' + currentValue;
}

// now, let's call the function in a forEach method 
names.forEach(bePresidential);

console.log(names);

// result:
// ["President Buhari","President Trump","President Tinubu","President Biden","President Obasanjo","President Obama"]

In the code example above, bePresidential is a function that takes 3 arguments:

  • currentValue - This is a representation of each element in the array given

  • index - This is the numerical position of each currentValue in the array

  • array - This is the data structure/container that holds the elements we want to add 'President' to.

For clarification, the code example above is similar to the following:

 let names = ['Buhari', 'Trump', 'Tinubu', 'Biden', 'Obasanjo', 'Obama'];

// using forEach, we can add 'President' to the names
names.forEach(function (currentValue, index, array){
    array[index] = 'President ' + currentValue;
});

// Arrow function
names.forEach(currentValue, index, array) => {
    array[index] = 'President ' + currentValue;
});

console.log(names);

// they will all produce the following result:
// ["President Buhari","President Trump","President Tinubu","President Biden","President Obasanjo","President Obama"]

With the examples above, it is clear that as JavaScript programmers, we have quite the array of tools to perform repetitive tasks with few lines of code. However, while we truly have these tools, it becomes a point of pain sometimes to know which to use at a particular time. One might even question why we have so many of them and not one since they perform the same task. These questions point to something: the mere existence of the various ways of looping means there are differences in how they operate and their use cases. In our case, we will consider when to use either of the for loop or forEach method.

The use cases between the For loop and the forEach method:

We have learned the concept of these iteration techniques and we have seen that either in their complexities or simplicities, they tend to programmatically perform a repetitive task while ensuring minimal and efficient code.

However, there are differences between these two techniques. Some of them will be discussed below.

Performance and Efficiency

The for loop is more efficient since it directly accesses elements by their index. This allows for efficient iteration, especially when dealing with large arrays or when performance is a critical concern.

The forEach method is less performant when compared to the for loop since it is a higher-order function and has to call a callback function on every element of the array. While the performance difference might be ignored when dealing with small arrays, it might not be the case when working with large arrays. Regardless, such concern can be negligible in most cases.

Break and Continue statements

The break and continue statements are used in a loop to alter the flow of the execution of the loop. When it is important to prematurely exit the loop when a condition is met, the break statement is used.

On the other hand, when we don't want to break out of the loop but skip an iteration when a condition is met and continue on the next iteration, the continue statement is used.

While using the for loop, there is access to the break and continue statements to break out of the loop upon a condition or skip a particular step, respectively. However, these statements are not available while using the forEach method. Hence, where early termination of the loop is a necessity, the for loop is suitable to use.

Asynchronous Operations

When working with asynchronous operations and the await statement, we want promises to be resolved and get their fulfillment value.

Using await inside the forEach method will not produce the expected result because it is not designed to handle asynchronous operations in this manner. The reason for this is that it does not wait for the promises to resolve or handle them properly.

Consequently, it is suitable to use the for loop to achieve asynchronous operations since it allows us to use the await statement inside the loop, which makes it wait for each Promise to resolve before moving on to the next iteration.

Callback Operations

When callback functions are needed to be called on each element of an array, the forEach method can offer a more functional and declarative style.

We could try to achieve the same with the for loop, however, the difference will stand out in terms of code readability, concise program, and declarative style

Conclusion

In conclusion, using either of these loops depends on what you are trying to achieve with your program/code, hence, a proper understanding and complexity of your program and how you want your repetitive task to be performed will guide you on which loop to use as you have learned in this article.

With this illumination on these loops, their differences, and their best use cases, you can improve your code writing skills and be assured that you are keeping to the best practices.

PS: How will you write Svelte is sweeter than React 100 times?