The initialization is used to set up a variable that will act as a counter. The condition is the expression we want to evaluate each time we pass through the loop. The loop will continue to process as long as the condition evaluates to true. If the condition expression evaluates to false the loop will exit. Iteration is an expression that executes at the end of each loop. Usually this increments (or decrements) the initialization value. The loop body is the code that runs each loop through. It is important to note that this loop only gives you access to the index in the array.
The below example is very simple for loop that multiplies each element in the nums array by two. We let i equal 0 and while i is less than the length of the nums array we continue to iterate over each element in the array, adding one to i each loop pass.
This logs 2, 4, 6, 10, 20 to the console.
There are many types of objects in JS. There will be times when you need to access all values in nested objects. We can use nested loops to access all the values within these special objects.
We have an array that contains three arrays, with two elements each. Our first (outer) for loop will iterate over the three arrays contained within the outer most array. So on our first loop cycle would be [1, 2]. Now we initiate another for loop on the current element we are on, [1, 2]. We can now do whatever we want to each individual element, let’s console log all our values.
First pass at i=0, nums[i] = [1, 2]
Handle inner array, nums[i].length is 2, j=0
Console.log(nums[i][j]) => [1, 2][j] => 1
After all passes the console should show 1, 2, 3, 4, 5, 6
There are two other types of for loops, for…in and forEach(). These two loops are similar to the ones above. For…in works similarly to the regular for loop, and forEach() works similarly to for…of. Note that they are not exactly the same.
One quick problem
Let’s look at a popular beginner coding challenge, Two Sum. We have an array of numbers and a target. We want to find items that when added equal the target. The indices should be returned in a tuple format.
There are more complex data structures that can solve this problem, but I believe this is a good introduction in critically thinking about how to solve problems using code. If you want to see other ways to solve this problem using a more complex data structure check out this problem on leet code.
If you have just begun on your coding journey, you will find that for loops are extremely useful when working with objects. And if you decide to pursue a career in coding you will find loops are at the core of many problems, especially problems you will need to solve to land a job as an engineer.