Playing around with for loop statements in javascript.
Tags: javascript, beginners, discuss, api
Published: 2022-07-09 02:48:00


Loops are handy when you want to run the same code over and over again, and it's specially used with arrays.

We'll explore the 3 for statements loops
* FOR
* FOR IN
* FOR OF


Just for fun i'm using the PokéAPI (https://pokeapi.co/), It's an easy to use and  funny API where we can get and iterate over pokemons names :rocket:

We can make our api call like this:
```javascript
const axios = require('axios')
const baseURL = `https://pokeapi.co/api/v2`

async function obterPokemon() {
  const request = await axios.get(`${baseURL}/pokemon/?limit=150`)
  const pokemons = request.data.results
  return pokemons
}
```
Passing a `console.log(pokemons)`, we see that the API return an array of objects, for example: 
```javascript
[
  { name: 'bulbasaur', url: 'https://pokeapi.co/api/v2/pokemon/1/' },
  { name: 'ivysaur', url: 'https://pokeapi.co/api/v2/pokemon/2/' },
  { name: 'venusaur', url: 'https://pokeapi.co/api/v2/pokemon/3/' },
  { name: 'charmander', url: 'https://pokeapi.co/api/v2/pokemon/4/' },
  { name: 'charmeleon', url: 'https://pokeapi.co/api/v2/pokemon/5/' },
  ... 145 more items
]
```
...

Our job today is to iterated over this array using the 3 distinct "FORS".


> ## FOR

**Sintax**
`for ([initialization]; [condition]; [final expression])
   {declaration}`

The for loop statement creates a loop that consists in 3 optional expressions and a required declaration.

**Initialization**
Usually represented by a var with a initial value, `let i = 0` for example.

**Condition**
This part is responsible for maintaining the code running or break it, usually represented by the object of initialization(in this case "i") and an array or something with an number greater than 0, `i <= array.length` for example.

**Final Expression**
This folk makes the loop number up or down depending of what is passed, usually represented by `i++` ou `i--`

**Declaration**
In this part we could pass a condition that will be run until the loop is over. They must be passed inside brackets after the for statement.

....

Let's jump to code! Here we'll do a little iteration using the traditional "for"

```javascript
async function getPokemons() {
const request = await axios.get(`${baseURL}/pokemon/?limit=150`)
const pokemons = request.data.results

console.time('FOR - RUNTIME')
const pokemonNames = []
  
     for (let i = 0; i < pokemons.length; i++) {
       pokemonNames.push(pokemons[i].name)
     }

console.log(pokemonNames)
console.timeEnd('FOR - RUNTIME')
}

getPokemons()
```

**RETURN IN TERMINAL**
![TERMINAL](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y5ai1gqscrsz1d2xyoi6.png)
 
> I did 5 tests and they all took about 13ms with an average of 13.749ms

---

> ## FOR IN

**Sintax**
`for (variable in object) {...}`

The FOR IN loop interacts above the enumerated properties of an object, in the same order of insertion . I'ts almost the same as FOR but the sintax is more clean to use. Here we only have 2 parameters, besides the declaration.

**Variable**
It's easy, represents an "unique" property of an object.

**Object**
The object we want to iterate.

...

Let's do the same iteration we do above with the same array, but using FOR IN.

```javascript
async function getPokemons() {
  const request = await axios.get(`${baseURL}/pokemon/?limit=150`)
  const pokemons = request.data.results

  console.time('FOR IN - RUNTIME')
  const pokemonNames = []

        for (let i in pokemons) {
          pokemonNames.push(pokemons[i].name)
        }

  console.log(pokemonNames)
  console.timeEnd('FOR IN - RUNTIME')
}

getPokemons()
```

**RETURN IN TERMINAL**
![TERMINAL](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gay0px39pmxuqury2dox.png)
 
> I did 5 tests and they all took about 13ms with an average of 13.431ms

---

> ## FOR OF

**Sintax**
`for (variable of iterable) {declaration}`

The FOR OF loop iterates over more types of collections, he calls a function with instructions to be run in every distinct value of an object and has 2 parameters and the declaration.

**Variable**
On each iteration a value of different property is assigned to this variable.

**The Iterable**
The object we want to iterate.

...

A little change in the code and we have!

```javascript
async function getPokemons() {
  const request = await axios.get(`${baseURL}/pokemon/?limit=150`)
  const pokemons = request.data.results

  console.time('FOR OF - RUNTIME')
  const pokemonNames = []

        for (let pokemon of pokemons) {
          pokemonNames.push(pokemon.name)
        }

  console.log(pokemonNames)
  console.timeEnd('FOR OF - RUNTIME')
}

getPokemons()
```

**RETURN IN TERMINAL**
![TERMINAL](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5yv2kg0s01n9vm4dtkfi.png)
 
> I did 5 tests and they all took about 13ms with an average of 13.550ms

---

**IN RESUME**
With the results we can see that the difference between FOR loops is much more than performance, every loop has its details and singularities.

The FOR OF loop does make our lives easier, but even in milliseconds we could see that FOR IN is slightly faster.

---

**BONUS**
Console.log has influence in code

**With** console.log(5 runs)
FOR = 13.749ms
FOR IN = 13.431ms
FOR OF = 13.550ms

**Without** console.log(5 runs)
FOR = 1,011ms
FOR IN =  0,386ms
FOR OF = 0,414ms

That's all for now, thanks for reading...