Loops in JavaScript

busayo2605

Lamina Busayo

Posted on July 14, 2023

Loops in JavaScript

loops are used in javaScript to perform repeated task based on condition. conditioons typically returns true or false. A loop will continue running until the defined condition returns false.
This concept will explianed using an array of strings

const people = ['Sam', 'John', 'Sylvia', 'Steve']
Enter fullscreen mode Exit fullscreen mode

To iterate over an Array means to loop through an Array’s contents. There are majorly 7 types of loops in javaScript. To get the most out of this article, you will need to understand concepts like Array, String, and Function. If you don’t, you will need to take a step back to have an understanding on the aformentioned concecpts. If you do, let’s get started.

For Loop

Let’s start with the most common and the oldest loop, the For Loop. This is what it looks like:

for (let i = 0; i < people.length; i++) {
    console.log(people[i])
}

//output
    //Sam
    //John
    //Sylvia
    //Steve

Enter fullscreen mode Exit fullscreen mode

You can see in the above that between the brackets there are three required attributes, these are:

  • Let i = 0; – This creates a new variable that we increment on every loop. “i” represents the Index and we use this variable to access the people in the array.
  • i < people.length; – This is a conditional statement. This code tells the engine to keep looping as long as “i” is less than the Array size.
  • i++; – This last attribute is shorthand to increment i. It is the same as writing i = i+1. It will add 1 to “i” on every loop. In our example, the above loop will loop through each emoji and then print the people to the console:

This basic For loop will run anywhere you can execute JavaScript. You can always rely on this to be available in any browser.

Sometimes you need to loop until you find an element in the Array. To do this we can use a Break statement.

Break

Break will stop the For loop from running. This is useful when you are trying to find a value in a large Array. For example, say that we were not sure where the string Sylvia was in our Array and we wanted to loop until we found it.
Well, we could write code like this:

for (let i = 0; i < people.length; i++) {
    if (people[i] === 'Sylvia'){
        break
    }   
    console.log(people[i])
}

//output
    //Sam
    //John
    //Sylvia


Enter fullscreen mode Exit fullscreen mode

As soon as we match the the string Sylvia the loop stops.

What if we wanted to perform an operation on all the values in the Array except one? In this case, we could use Continue.

Continue

Continue is like a Break statement but instead of stopping the loop it can skip or “jump over” an item in the array.

This time we are going to write the code so that when we find the string Sylvia, we skip it and we won’t print it to the console:

    for (let i = 0; i < people.length; i++) {
        if (people[i] === 'Sylvia'){
            break
        }   
        console.log(people[i])
    }

    //output
        //Sam
        //John
        //Steve


Enter fullscreen mode Exit fullscreen mode

As you can see, the code is almost the same as the prior example, except that this time we have replaced Break with Continue. The outcome is different:
The string Sylvia has not been printed as expected. You can use Continue to filter an Array and only perform an operation on some of the items.

For..In

We have looked at traditional For loops, but there are shorter versions. We can use a For..in loop to loop through an Array like this:

    for (const i in people) {
        console.log(people[i])
    }

Enter fullscreen mode Exit fullscreen mode

This is shorter code and there is no need to increment the index using the i++ code. So why not use this loop all the time?
There is a problem with For..in.
You see, it is possible to extend a built-in object like Array. For example, I can create a custom operation on an Array, like this:

Array.prototype.foo = 1
for (const i in people) {
      console.log(people[i])
}

//output
    //Sam
    //John
    //Sylvia
    //Steve
    //foo

Enter fullscreen mode Exit fullscreen mode

Now when you run the code this is the output:
The foo function is part of the loop! For this reason, you should never use For..in in your code.

We have discussed the basic For loops—next, we will look at While loops.

While Loop

A While Loop will continue to loop while a condition is true.

For example, the below code will loop while “i” is less than the Array size:

i = 0 
while (i < people.length){
    console.log(people[i])
    i++
}
Enter fullscreen mode Exit fullscreen mode

We are doing the same thing as we were in the For loop:

  • i = 0 – Creating an index variable and setting it to 0.
  • i < emojis.length – Looping while i is less than emojis.length
  • console.log(emojis[i]) – printing each emoji String to the console.
  • i++ – Incrementing the index by 1 on each loop. This code will print all the people.

Why would you use a While loop over a For loop?

Although they are interchangeable, you will not see While loops very often in JavaScript code. But, they can be useful. For example, say we are not sure what position the string John is in. We want to loop until we see a John. This is what the code will look like:

let i = 0
let noJohn = true 
while (noJohn){
    console.log(people[i])
    i++
    if (people[i] === 'John') {

        noJohn = false
    }
}
Enter fullscreen mode Exit fullscreen mode

For each loop, we check the condition (noJohn) and if it is ‘true,’ then the loop continues. As soon as ‘noJohn’ is set to false the loop will stop. This is like the break statement For loop we used above.

What if you wanted to check the conditional after the loop? Well, in that case, you need a Do/While loop.

Do/While Loop

This loop is almost identical to the while loop, except the condition check is at the end. This is what the code will look like:

let i = 0 
do {
    console.log(people[i])
    i++
} while (i < people.length)
Enter fullscreen mode Exit fullscreen mode

The code will run in this flow:

Set the index to 0
Print the first element in the Array using console.log
Add 1 to the index
Then check is index is still less than the size of the Array

ES5

All the loops we have discussed so far are available in any JavaScript environment. In front-end development, we need to think about browser support. Over the last few years, there have been many advances in the JavaScript language. There are new loops available.

The first changes came in ES5, which means version 5 of JavaScript. The new loops are:

  • forEach
  • map
    For both of these are operations, you can call on an Array. For the people Array, it would look like this:

  • people.forEach()

  • people.map()

Let’s look at these more in depth.

forEach

forEach is a function added to the Array type. The function takes a callback function, which is a block of code, like this:

people.forEach(person => console.log(person))
Enter fullscreen mode Exit fullscreen mode

For every value inside the Array, it will run the callback block you pass inside the brackets. This is a nice way to do For loops in ES5.

If forEach is available, then this is the recommended way to do a loop.

Map

You can loop using a Map function the same way as forEach by passing a callback. The map function then calls this callback for every item in the Array.

people.map(person => console.log(person))
Enter fullscreen mode Exit fullscreen mode

The difference with Map is that it returns an Array. This function can convert the contents of one Array to another. For example, if we wanted to create a new Array with all the people as John, we could run this code:

const johns = people.map(person => 'John')

console.log(johns)

//output
    //['John', 'John', 'John', 'John']

Enter fullscreen mode Exit fullscreen mode

Use this Loop when you need to create a new array from an existing one. This can be a very powerful loop when combined with reduce.

ES6

The last loop we are going to look at is part of ES6.

This is the For..of loop.

This loop addresses the shortcomings of “For..In” and has similar code syntax.

The browser support for ES6 is getting better yet IE is a bit behind. This means you may not be able to use For..of if you need to support the IE browser.

For..of

Like the For..of loop the code looks like this:

for (person of people) {
    console.log(person)
}

Enter fullscreen mode Exit fullscreen mode

This does not have the same problem as the For..in loop. Anything added to the Array will not appear in the loop. If you are in an ES6 environment, then you can and should use this loop.

conclusion

We have looked at the major loops that you can use in Javascript.

If you do not have ES5 or ES6, then you can use the traditional For loop or a While loop.

If you have ES5, then you can use either forEach or Map. If you are only supporting the latest browsers and have ES6, then you can look at using For..of.

Whatever you do, don’t use For..in!

💖 💪 🙅 🚩
busayo2605
Lamina Busayo

Posted on July 14, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related