JavaScript: 6 types of Loops you should know about.
Tags: javascript, beginners, programming, tutorial
Published: 2023-08-23 16:33:37

For any programmer, being able to use loops effectively is a fundamental skill. In order to improve the effectiveness, readability, and capacity of your code to handle repetitive tasks without the need for writing redundant code, loops are an essential tool.
When specific conditions are met, loops can even be used to perform a series of tasks while iterating over values of an array.

The most common type of loops that you've probably already seen are `for`, `while` and `do while` that you've probably already encountered are covered in this article along with 3 other types of loops:

1. [For loop](#for)
2. [while loop](#while)
3. [do while loop](#do-while)
4. [for-in loop](#for-in)
5. [for-of loop](#for-of)
6. [break statement](#break)
7. [continue statement](#continue)
8. [labeled loop](#label)

## <a id="for">For Loop </a>

The `for` loop allows you to run a block of code over and over for a specified amount of iterations. It is especially useful When you know exactly how many times you want the loop to run. 

### The for loop structure
The structure of a `for` loop is made up of 3 parts: 
1. initialization : The initialization is a variable that gets initialized to keep track of the number of iteration (cycle) we're at. This is commonly used as a counter.
2. condition: this is a condition that is checked at the beginning of each iteration (cycle). As long as the condition is `true`, the loop continues to execute.
3. increment and decrement: After each iteration, the increment or decrement change the loop control variable(which is a variable inside the loop that instructs the loop whether to stop or continue executing), to make the condition false and end the loop.

```javascript
for (initialization; condition; increment/decrement) {
    // Code 
}
```
Let's print the number 1 through 5 in our console using the `for` loop

```javascript
for (let i = 1; i <= 5; i++) {
    console.log(i);
}
/*
1
2
3
4
5
*/
```
In this example :
- The i variable is initialized to 1.
- The loop will keep running as long as i is less than or equal to `5`.
- After each iteration, i is incremented by 1.
The loop will print the numbers 1 through 5.

Let's take another example, this time using an array.

```javascript
const foods = ['ice cream', 'cheese', 'milk', 'bread', 'chocolate'];

for(let i=0; i<foods.length; i++){
   console.log(foods[i]);
}
/*
ice cream
cheese
milk
bread
chocolate
*/
```
In the example above:
- The i variable is initialized to 0.
- The loop will keep running as long as i is less than the length of food which is `5`.
- After each iteration, i is incremented by 1.
The loop will print each value in the array `foods`.

`foods[i]` might seem a bit unclear, remember the `i` represent a counter, so at 0 you're printing foods[0] which is `ice cream` then `i++` will increment `i` by 1 which makes `i=1`, so now what is being printed is `foods[1]` 

## <a id="while"> While loop</a>
The while loop executes a block of code repeatedly if the condition that was passed to it is `true`. Unlike the `for` loop, only a single condition is provided to it which is evaluated before each iteration (cycle).

### Syntax of a while loop
``` javascript
let counter = 0;
while(condition){
  //code
}
```

Let's reprint the numbers 1 through 5 again this time using while loop.

```javascript

let counter = 1;

while(counter<=5){
    console.log(counter);
    counter++;
}
/*
1
2
3
4
5
*/
```
- In the example above we initialized a counter outside the `while` loop and set it to 1. 
- Then we passed the condition `counter<=5` to the `while` loop to be evaluated. So as long as the counter is less than or equal to 5 the `while` loop will keep executing.
- We `console.log(counter)` to the console which will print the numbers from 1 to 5.
- the `counter++` is where we increment the `counter` variable and this is a very important step.

**If you forget to increment the counter variable you will have something called an `infinite loop` which means your program will run indefinitely causing your program to become unresponsive and crash.**

Let's use our foods array example with a while loop now. 

```javascript
const foods = ['ice cream', 'cheese', 'milk', 'bread', 'chocolate'];

let counter = 0; 

while(counter<foods.length) {
    console.log(foods[counter]);
    counter++;
}
/*
ice cream
cheese
milk
bread
chocolate
*/
```

- In this example we declared a variable `counter` outside the `while` loop (you can name the variable whatever you'd like).
- We passed the condition `counter<foods.length` to the loop which basically means that, as long as the counter is less than `5` print the values inside the foods array. 
- Then we incremented the counter `counter++`.

## <a id="do-while">The Do...while loop</a>
The `do...while` loop is the same as the `while` loop with only one difference is that the condition is checked after the block of code is run whether the condition was met or not.

Let's look at an example where the condition evaluates to `false` to understand how this works.

```javascript
let i = 12; 
do {
    console.log(i); //12
    i++;
}
while(i<=5);

```
In this example, `12` gets printed to the console then the `do...while` loop stops executing because `i<=5` evaluates to false.

```javascript
let i = 1; 
do {
    console.log(i);
    i++;
}
while(i<=5);
```
Here the loop will print the numbers from 1 to 5.

## <a id="for-in">For...in loop</a>
The `for...in` loop is usually used to iterate through the properties of an object Which we'll be seeing in an upcoming article. 
For the sake of this tutorial we'll demonstrate the use of the `for...in` loop using an array but it is not recommended doing so because it can lead to some unexpected behavior.

```javascript
const fruits = ["apple", "banana", "orange"];

for (const index in fruits) {
    console.log(index, fruits[index]);
}
/*
0 apple
1 banana
2 orange
*/
```
In the example above the `fruits` is the array that we're iterating over and `index` is the current element of the `fruits` array in the `(const index in fruits)`. The loop continues to iterate until all the elements of the array `fruits` are printed to the console.

## <a id=="for-of">The for...of</a>
The `for...of` loop makes it possible to iterate through objects, arrays, strings and more. It is a simpler and more readable way to loop over iterables than a regular for loop. 

```javascript
const fruits = ["apple", "banana", "orange"];

for (const fruit of fruits) {
    console.log(fruit);
}
/*
apple
banana
orange
*/
```


## <a id="break">Break statement</a>
The `break` statement is a control statement that is used to abruptly end the execution of a loop.

```javascript
for (let i = 1; i <= 5; i++) {
    if (i === 3) {
        break;
    }
    console.log(i);
}

/*
1
2
*/
```
In the example above, we're printing the numbers from 1 to 5 using a `for` loop. 
The execution of this loop abruptly stops when it reaches the number three. That is because we've added a condition inside the loop `if (i === 3)` that checks if the counter `i` is 3 and if the condition evaluates to `true` the `break` statement is used to exit the loop which stops its execution.

Let's use it with the `fruits` array. 

```javascript
const fruits = ["apple", "banana", "orange"];

for(let i=0; i<fruits.length; i++) {
    if(fruits[i] === "banana") {
        break;
    }
    console.log(fruits[i]);
}

//apple
```
Here as you probably can tell, we're iterating through the `fruits` array and printing its values to the console. A condition is added inside the loop asking to check each items at `fruits[i]` to see if it is equal to `banana`. 
if the condition evaluates to false, it will print the value at the current position of `fruits[i]` if it evaluates to true it will break out of the loop and stop its execution.

## <a id="continue">Continue Statement</a>
The `continue` statement is a control statement that is used to move to the next iteration of a loop while skipping the current iteration.

```javascript
for(let i=0; i<=5; i++) {
    if(i ==3) {
        continue;
    }
    console.log(i);
}
/*
1
2
4
5
*/
```
In the example above, we're using a `for` loop and we've added a condition to see if the counter `i` is equal to 3. if the condition evaluates to true, we skip over `3` and don't print it and continue with the loop.

Let's try this with the `fruits` array.

```javascript
const fruits = ["apple", "banana", "orange"];

for(let i=0; i<fruits.length; i++) {
    if(fruits[i] === "banana") {
        continue;
    }
    console.log(fruits[i]);
}
/*
apple
orange
*/
```

As we can see when the condition `fruits[i]==="banana"` is satisfied, the loop skips over printing the value banana and keeps on executing until the condition in the for loop evaluates to false that is `i<fruits.length`.


## <a id="label">Labeled loop</a>
The `labeled` loop has a label assigned to it. It it is mostly used with `break` and `continue` statements in order to identify the loop.

```javascript
mainLoop: for (let i = 1; i <= 3; i++) {
    console.log("Main loop iteration:", i);

    nestedLoop: for (let j = 1; j <= 3; j++) {
        console.log("Nested loop iteration:", j);

        if (i === 2 && j === 2) {
            console.log("Breaking out of main loop!");
            break mainLoop;
        }
    }
}
/*
Main loop iteration: 1
Nested loop iteration: 1
Nested loop iteration: 2
Nested loop iteration: 3
Main loop iteration: 2
Nested loop iteration: 1
Nested loop iteration: 2
Breaking out of main loop!
*/
```