3 Kinds of Loops That We Use All The Time Without Knowing Their Names.
Tags: javascript, programming, loops, webdev
Published: 2023-03-02 15:52:20

Loops are an integral part of programming. Without them, we can't even think of the modern era of computing that we all live in today. *Seriously!*

They are the heart of computer automation that help us automate a lot of stuff quite nicely and intuitively.

As far as writing loops is concerned, there are three extremely common types of loops that we use in many programs, often without being aware of the exact kind of loop that we're using.

Those three types are as follows:

- **Counter-based loops**
- **Input-validation loops**
- **Sentinel-controlled loops**

Let's explore each one of these, in detail.

-----

## Counter-based loops

As the name suggests, **counter-based loops** are loops that are based on a *counter*. A counter is simply a variable to help keep track of incremental (or decremental) numbers.

The most typical example of a counter-based loop is a `for` loop to iterate over all the elements of a given array.

In such a loop, the counter is typically taken to be `i`, beginning at `0`, ending at the index of the last element in the array, and incrementing by 1 with each subsequent iteration.

Below is an example of a counter-based loop:

```javascript
var nums = [1, 2, 3];
// Counter-based loop.
for (var i = 0; i < nums.length; i++) {
   console.log(nums[i]);
}
```

A counter-based loop doesn't always have to increment. It can even decrement, as shown below:

```javascript
var nums = [1, 2, 3];
// Decrementing counter-based loop.
for (var i = nums.length - 1; i !== 0; i--) {
   console.log(nums[i]);
}
```

Time to move to the next type, i.e. input-validation loops.

-----

## Input validation loops

**Input validation** loops are meant to keep running unless a given piece of input is valid.

They are typically powered by a `while` loop, since the number of iterations after which the given input will become valid is unknown, and iterating an unknown number of times is what `while` should be used for.

Input validation loops are common when developing CLI programs where input is routinely obtained from the user.

Below is an example of an input validation loop in JavaScript that is meant to let only numeric inputs pass through it:

```javascript
var input = Number(prompt('Enter a number'));
while (isNaN(input)) {
   alert('Invalid input.')
   input = Number(prompt('Enter a number'));
}
console.log('The number is:', input);
```

-----

## Sentinel-controlled loops

A **sentinel-controlled loop** is one where the execution continues as long as the entered value is not a given *sentinel*.

A sentinel is simply a special value that's there for a special purpose.

For instance, suppose that a program asks the user to input a list of positive numbers to add. A sensible sentinel value could be `-1` — the input of this value would signal the end of the list of numbers.

Sentinel-controlled loops are also extremely common in CLI programs.

Remember the idea of entering `quit` or `exit` in a CLI application to exit the window? This is an instance of a sentinel-controlled loop that runs until we enter the value `quit` or `exit` as input.

Below is an illustration of a sentinel-controlled loop in JavaScript that's meant to end when the given input is `-1`:

```javascript
var sum = 0;
var input = prompt('Enter a number, -1 to exit.');
while (input !== '-1') {
   sum += Number(input);
   input = prompt('Enter a number, -1 to exit.');
}
alert(`The sum is ${sum}.`);
```

-----

## In the end…

Loops are of immense importance in the world of computing. Likewise, needless to say, all programmers must perfect them to the core.

To explore more details about working with loops in JavaScript, refer to the following chapters in our [comprehensive JavaScript course](https://www.codeguage.com/courses/js/):

- [The for loop](https://www.codeguage.com/courses/js/loops-for-loop)
- [The while loop](https://www.codeguage.com/courses/js/loops-while-loop)

Once you're done learning the bits and pieces of these simple loops, there are even some exercises to try out:

1. [Multiply All](https://www.codeguage.com/courses/js/loops-multiply-all-exercise)
2. [Greatest Common Divisor](https://www.codeguage.com/courses/js/loops-greatest-common-divisor-exercise)
3. [Selection Sort](https://www.codeguage.com/courses/js/loops-selection-sort-exercise)
4. [Collatz Conjecture](https://www.codeguage.com/courses/js/loops-collatz-conjecture-exercise)