Skip to main content

Command Palette

Search for a command to run...

Understanding For Loops in JavaScript

Analysing the role of loop control variables in manipulating Arrays

Updated
6 min read
Understanding For Loops in JavaScript
C

I am Deborah, a Software Developer From Nigeria. As a Tech Enthusiast, I love to write about the latest advancements in technology. From Software Development to Cloud Computing, Cybersecurity, Cryptography and Blockchain Technology, I cover a wide range of topics in a clear and concise manner. Join me on my journey as I explore fascinating concepts in computer technology and share my insights with you. Follow my blog for regular updates and stay up-to-date on the latest tech trends!

The for loop is a control flow statement that allows a block of code to be executed multiple times until a condition is met. It consists of three main components: the initialization, the condition and the iteration.

The general syntax of a for loop in JavaScript is as follows:

for (initialization; condition; iteration) {

    // code to be executed or run - The loop body

}

The order of execution within a for loop follows a specific sequence. Let's break it down step-by-step:

1. Initialization:

This part is executed first and only once at the beginning of the loop. It is typically used to initialize (set the initial value of) the loop control variable `i`, which is typically a counter. For example, `let i = 0` initializes the the loop control variable `i` to 0. This means it sets it's count start to 0.

2. Condition:

After initialization, the loop condition is checked. The condition is evaluated before each loop iteration. The loop body is executed if the condition is true. The program continues with the next statement after the loop as soon as the condition is false. It is commonly used to check if the loop control variable has reached a certain value or satisfies a specific condition. For example, `i < array.length` checks if the loop control variable is less than the length of the array.

3. Loop Body Execution:

If the condition is true, the code within the loop body is executed. This code block contains the statements you want to repeatedly execute as part of the loop.

4. Iteration:

In the context of computing, programming and loops, iteration refers to the process of repeatedly executing a block of code as long as a condition is true. It involves going through a sequence of steps multiple times. Think of it as a loop that allows you to perform an instruction or a set of instructions repeatedly until a specific condition is met.

This part of the for loop is executed after the loop body has been executed. It is typically used to update the loop control variable. For example `i++` increments the index of the loop control variable `i` by 1.

5. Condition Recheck:

Once the iteration part has been executed, the condition is rechecked. The loop body is rerun if the condition is true. A false condition terminates the loop, and the program proceeds to the next statement.

This sequence of execution allows the loop to repeatedly execute the code within the loop body until the condition becomes false.

To summarize, the order of the execution within the for loop is: initialization -> condition check -> loop body execution -> iteration -> condition recheck.

Now let's see how the loop control variable affects arrays in for loops:

One of the most common uses of for loops with arrays is to iterate over each element of the array. When we say 'iterate over', we mean go through each item or element in a collection, such as an array or a list in a sequential order, until a condition is met and perform an action on each of them (usually, the code to be executed and contained within the loop body). It's like visiting each item in a group, one by one, and doing something with it. It allows you to process or examine each element individually within the collection.

In for loops, the loop control variable `i` acts as an index or position to access the elements of an array. By initializing it and using it within the bracket notation `[i]` in the loop body, you can dynamically access different elements of the array during each iteration of the loop. The loop control variable takes on different values as the loop iterates, and these values are used as the index inside the square brackets `[i]`. Since the elements of an array are accessed by their specific indexes using bracket notation, `i` serves as a dynamic index that allows you to access different elements of the array sequentially, in each iteration.

Usually, indexing in Arrays begins at 0. This means the first element of any data set in an array has an index of 0, and the next element occupies it position in an incremental order, succeeding the previous element.

In the example below, `array[i]` gives us the value of the element at index `i` in the array. By manipulating the loop control variable within the iteration part of the for loop, we can control how the elements of the array are accessed. For instance, we can iterate backwards through the array by decrementing the loop control variable (`i--`) instead of incrementing it.

Keep it in mind that the loop control variable can have any name you choose. Using meaningful names, such as `index` or `item`, can make your code more readable and maintainable.

consider the following example:




        const array = [2, 4, 6, 8, 10];

        for (i = 0; i < array.length; i++) {

            console.log(array[i]); // the action to be performed on each item. It is the Loop body to be executed or run.

        }

This is what would be shown at the console:

        2

        4

        6

        8

        10

Here is how it works:

The loop control variable `i` is set to 0. Do not forget that it is a counter. You are therefore, telling the loop control variable to start counting from 0.

array.length = 5. The .length property does not use the 0 indexing, it counts from 1. It is used to display the total number of elements in an array or variable. Hence, its counting from 1. The condition `i < array.length` checks if `i` is less than the length of the array.

The first element which is 2 is at an index of 0

The second element which is 4 is at an index of 1.

The third element which is 6 is at an index of 2.

The fourth element which is 8 is at an index of 3.

The fifth element which is 10 is at an index of 4.

By using `array[i]` within the for loop, we access the element at the current index `i` of the array. `console.log(array[i])` prints the element at the current index `i` to the console, after which the iteration is executed.

Since `i` has been initialized to begin it's count from index 0, during the first iteration, 0 < 5, console.log(array[0]) = 2

In the second iteration, i++ goes to the element at the next index which is 1, 1 < 5, console.log(array[1]) = 4

In the third iteration, i++ goes to the element at the next index which is 2, 2 < 5, console.log(array[2]) = 6

In the fourth iteration, i++ goes to the element at the next index which is 3, 3 < 5, console.log(array[3]) = 8

In the fifth iteration, i++ goes to the element at the next index which is 4, 4 < 5, console.log(array[4]) = 10

As can be seen, the loop continued until `i` reached its maximum index (4) which is less than the length of the array (5 in this case), and thus all the elements of the array are accessed at their various indexes and printed to the console using `console.log(array[i])`.

In summary, the loop control variable `i` is responsible for accessing the elements of the array sequentially. By incrementing `i` within the loop, we move through the array, accessing each element one by one until the loop condition is no longer met.

S

Nicely written

1
C

Thanks Favour

A

Thanks for sharing this informative post about for loops in JavaScript! I found your explanations and examples to be quite helpful in understanding the concept. For loops are indeed a fundamental tool in JavaScript programming, and your breakdown of the initialization, condition, and iteration steps made it easier to grasp the logic behind them.

While for loops are versatile and widely used, I personally prefer to use the forEach loop when iterating over arrays. The forEach loop provides a more concise syntax and simplifies the code by handling the iteration logic internally. It also allows me to focus more on the operations I want to perform on each element rather than managing the loop mechanics.

That being said, I still acknowledge the importance and usefulness of for loops, especially in scenarios where you need more control over the loop flow or when working with other data structures besides arrays. Your post does an excellent job of explaining the power and flexibility of for loops in such cases.

It would be great if you could consider covering the forEach loop as an alternative in a future blog post. Comparing the two approaches and discussing their respective strengths and use cases would provide readers with a more comprehensive understanding of different looping techniques in JavaScript.

Overall, your blog post is well-written and provides a solid foundation for understanding for loops in JavaScript. Keep up the good work, and I'm looking forward to exploring more of your JavaScript tutorials in the future!

1
C

Dear Alfred,

Thank you so much for taking the time to read and engage with my blog post on for loops in JavaScript. I greatly appreciate your thoughtful comment and feedback.

I'm glad to hear that the explanations and examples provided in the article were helpful in enhancing your understanding of for loops. They indeed form an essential tool in JavaScript programming, and breaking down the initialization, condition, and iteration steps is intended to simplify the logic behind them.

I completely understand your preference for using the forEach loop when iterating over arrays. Its concise syntax and internal handling of iteration logic can indeed simplify code and allow for a focus on the operations performed on each element. It's an excellent choice, especially for simpler iterations.

I genuinely appreciate your suggestion of covering the forEach loop as an alternative in a future blog post. I will definitely consider incorporating that topic into an upcoming tutorial.

Thank you again for your kind words and encouragement. I'm thrilled that you found the blog post well-written and informative. If you have any further questions or if there are specific topics you'd like me to explore in my future posts, please don't hesitate to let me know.

3