Iterations in Javascript

Using "for" loops

In programming we often need to iterate on a series of values. For example, we
may have to print out all the numbers in an array. Or we may have to multiply a series of numbers together.

One common way to iterate on a list is to use a for loop.
A for loop in Javascript has this structure:

for (  <1. initialize a counter>;
       <2. condition>;
       <3. increment the counter>) {

  <4. statement>

}

In step 1 we initialize a counter that will be used to keep track of our iteration. We typically set this to a variable called i
The variable name can be anything, but it's common to use the letter i for iterator. If you need more than one variable, you can use other names, like j, k, or anything else.

In this example below, we initialize the iterator to 0:

let i = 0

Step 2 is the condition that allows our loop to continue looping. As long as the
condition is true, our loop will keep going.
An example of a condition is:

i < array.length

Here we assume we have an array and check its length.
If the iterator i is less than the array length, the condition evaluates to true so we keep on looping.
If the iterator i reaches a higher value than the length of the array, the condition evaluates to false, and the loop stops.

In step 3 we increment the iterator. If the iterator was 0 at the beginning of the loop, in step 3 we may want to increment it to 1.
We do this with this syntax:

i++

If the iterator starts at 1, this code will increase it by 1 and will assign the value back to the iterator, so the iterator is now 2.
We don't have to increase it every time, we can decrease it or add 2 every time, like so:

i--    // decrease by 1
i + 2  // increase by 2 every time the loop executes

What we do depends on what we need to achieve in our loop.

Step 4 is the statement that will be executed each time the loop iterates. This can be any Javascript expression and it's the operation we need to complete for each iteration.

Let's see an example of loop in action.

Say we want to print out all the elements of an array. We set up a function called printArrayElements that takes an array as an argument and sets up a loop. The loop goes through all the elements and prints them to the console one by one.

const printArrayElements = array => {
  for (let i = 0; i < array.length; i++) {
    console.log("Array element:", array[i]);
  }
}

printArrayElements([1, 2, 4, 5]);
printArrayElements(['a', 'b', 'c', 'd']);

Tomorrow we will look at more complex examples of looping, but all for loops
work the same way under the hood.


Did you like this article? Share it with your friends.

Share

I write daily about front-end and back-end web technologies.
You can receive all my articles in your inbox by subscribing to my newsletter. Just click the button below. No spam, just good, useful content. Guaranteed!

Follow me on Twitter @CesareFerrari