How to write a for loop in Javascript: a too many ways guide
Tags: javascript, beginners, typescript, writing
Published: 2023-01-28 14:13:35

There’s a lot of possibilities and styles to write a loop in Javascript. In this article, I’ll show simple options, the readable options and least talked options.

### Summary
1. [Vanilla For loop](#vanilla-for-loop)
2. [While and Do-While Loop](#while-and-do-while-loop)
3. [Calling forEach](#calling-foreach)
4. [References](#references)

## Vanilla For loop

This examples are mostly shown in tutorials, Stackoverflow questions and documentation.

``` javascript
// Option 1: use a start and end value
for (i = startValue; i <= endValue; i++) {
	// Before the loop: i is set to startValue
	// After each iteration of the loop: i++ is executed
	// The loop continues as long as i <= endValue is true
}
```
**About the endValue:** If you want to check the array lenght you should use myArray.lenght
**About the i++:** it means i = i + 1, that increments one by one, you're also able to use i = i + anyValueYouWant

``` javascript
// Option 2: use a For … in , mostly used if you have an array
for (i in things) {
	// If things is an array, i will usually contain the array keys *not advised*
	// If things is an object, i will contain the member names
	// Either way, access values using: things[i]
}
```

``` javascript
// Option 3: use a For … of 
for (i of things) {
	// there's no need to use the index
	// i is actually the object
}
```

**Benefits**
✔️ Very easy to learn
✔️ Readable

**Downsides**
❌ Uses too many lines
❌ Not appropriate to deal with Promises and async functions

## While and Do-While Loop

You're also able to use the `while` to se a condition to your for loop, as long it's set the beggining value, the condition and the update.

``` javascript
let i =  0; // beginning value
while  (i < endValue)  { // condition to while stop
	// Do something
	i++; // the update
}
```

Another way is to use `do...while`, but remember the test condition is different from the `while`.  Check the documentation of [do...while](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/do...while) and [while](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while)

``` javascript
// Alternative: use a do.. while
let i = 0;
do  {
	// loop body
	i++;
}  while  (i > endValue);
```

**Benefits**
✔️ You learn to use `while` and `do..while`

**Downsides**
❌ Uses too many lines
❌ If you forget any of your setup, the `while` loop will run endlessly

## Calling forEach

When you're working with arrays, you might have found a whole set of method to deal with, one of them is `forEach`. ([Documentation link](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)).

``` javascript
myArray.forEach(element => {
	// Do your operation here
    console.log(element)
});
```

**Benefits**
✔️ Few lines of code
✔️ Loop through all the elements of your array

**Downsides**
❌ Not appropriate for Promises and aysnc functions ( instead use [Promise.all](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) )
❌ You shouldn't use in cases that don't actually need to cover other conditions

### If I can't use forEach, what should I do?

Follow this guide from [Stackoverflow discussion](https://stackoverflow.com/questions/9329446/loop-for-each-over-an-array-in-javascript), I'll share a fraction of great options thata lot of users shared.

> -   `every`  ([spec](https://tc39.es/ecma262/#sec-array.prototype.every)  |  [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every)) - stops looping the first time the callback returns a falsy value
>  -   `some`  ([spec](https://tc39.es/ecma262/#sec-array.prototype.some)  |  [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some)) - stops looping the first time the callback returns a truthy value
> -   `filter`  ([spec](https://tc39.es/ecma262/#sec-array.prototype.filter)  |  [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)) - creates a new array including elements where the callback returns a truthy value, omitting the ones where it doesn't
> -   `map`  ([spec](https://tc39.es/ecma262/#sec-array.prototype.map)  |  [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)) - creates a new array from the values returned by the callback
> -   `reduce`  ([spec](https://tc39.es/ecma262/#sec-array.prototype.reduce)  |  [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)) - builds up a value by repeatedly calling the callback, passing in previous values; see the spec for the details
> -   `reduceRight`  ([spec](https://tc39.es/ecma262/#sec-array.prototype.reduceright)  |  [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight)) - like  `reduce`, but works in descending rather than ascending order

## References

 1. [How do I build a loop in
    JavaScript?](https://stackoverflow.com/questions/52080/how-do-i-build-a-loop-in-javascript)
 2. [Javascript fundamentals:
        While-for](https://javascript.info/while-for) [Documentation of
        do...while](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/do...while)
 3. [Documentation of
        while](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while)
 4. [Documentation
        Array.prototype.forEach()](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)
 5. [Loop (for each) over an array in JavaScript](https://stackoverflow.com/questions/9329446/loop-for-each-over-an-array-in-javascript)