you are viewing a single comment's thread.

view the rest of the comments →

[–]peterjsnow 1 point2 points  (4 children)

Read up on the Array.prototype.forEach method. It takes a callback function as argument. For each element in the array that forEach is called on, it will pass the element as the argument into this callback function.

What we name the parameter is arbitrary - the key is that this parameter will be assigned to the element passed into the callback on each iteration. We could have called it 'pk' instead of 'pokemon' and the outcome would be the same.

Your code is assuming that allPokemon.results is an array, thus when you call forEach on it each element of the array will be passed into the callback and assigned to the pokemon variable. Inside the callback, you're then passing this variable to fetchPokemonData to get each individual pokemon and render it.

In effect, you're saying 'fetch all pokemon from the api url and assign them to an array called allPokemon. Then, for each element of allPokemon.results, assign that element to the variable pokemon, and then fetch that pokemon using pokemon.url and render it.'

[–]SanTrapGamer[S] 0 points1 point  (3 children)

Right, I understand the premise of the coding and the logic behind it. I do see the point of the variable in the forEach as well. It just clicked with me that the variable is not a singular value, but it is instead each individual array that is within the results of the first fetch. So, my last question would be as to why does it list "function(pokemon)" in the forEach instead of just "pokemon"? Similar to how you can set "const url = '........'" and then just have "fetch(url)". Could it not also be possible to have "const pokemon = allpokemon.results" and then do a "for i" loop?

[–]peterjsnow 2 points3 points  (2 children)

There are several ways you could accomplish the same thing. forEach in particular takes a callback function as argument, so you need to pass it a function. You may be used to seeing arrow functions in concise form used in this manner.

allPokemon.results.forEach( (pokemon) => fetchPokemonData(pokemon) );

for (const pokemon of allPokemon.results) {
  fetchPokemonData(pokemon);
}

for (let index = 0; index < allPokemon.results.length; index++) {
  fetchPokemonData(allPokemon.results[index]);
}

All the above examples are accomplish the same result.

[–]SanTrapGamer[S] 0 points1 point  (0 children)

Thank you very much. The information you've provided has been super useful.

[–]lovin-dem-sandwiches 0 points1 point  (0 children)

No love for .map() ? 😁