Iterators lesson : forEach() - question about the examples

On point 2 of the Iterators lesson, there are three examples of how to achieve the same thing using for.Each().

groceryItem appears in the first two examples. My question is what is groceryItem? Is it a parameter, an argument…? It hasn’t been declared beforehand, so what meaning has it got?

const groceries = ['brown sugar', 'salt', 'cranberries', 'walnuts'];

groceries.forEach(function(groceryItem) {
  console.log(groceryItem); } ):

And the other example

groceries.forEach(groceyItem => console.log(groceryItem));

Many thanks

groceryItem is a parameter, .forEach will loop over you array, and for each element in your array call your function, and pass the current value as argument to your groceryItem parameter.

groceryItem is a parameter to the callback function that is defined inside your forEach method. This can be any name you like, might as well be x. Similar to any other function.

Upon calling forEach it passes each item/element of the array as argument to the callback function.

2 Likes

@stetim94 hey I was already here and typing :stuck_out_tongue: Just got distracted in the process…

1 Like

Thank you both janneslohmejer and stetim94!

So, the function ‘knows’ which array I am referring to because it is a part of the variable groceries, and groceryItem is just a placeholder.

I really struggle to understand what is needed when and what role different things have in the syntax, but I guess it’s natural at the beginning!

Thank you very much for replying so promptly.

you call the method on the array:

groceries.forEach(callback)

just like you would call .toLowerCase (which hopefully have been taught) on a string:

"HELLO WORLD".toLowerCase()

if you had a different array (for example abc) and you want to call forEach method on array, you would do:

abc.forEach(callback)

THIS is the answer lacesser is looking for especially this part: “This can be any name you like, might as well be x .”
It confused me a lot when I started learning array methods too. It represents each element in the array.

2 Likes

Hello all

Thank you stetim94 for the clarification. And yes, as choomah_aj says, that was the main answer for me: that is just a name and it can be anything else, like x.

I’ll keep practising and hopefully one day I’ll understand it all :slight_smile:

Cheers

Not to complicate things, but another useful feature in the forEach iterator is the 2nd optional parameter (which is “hidden” so to speak). It’s an index or a "counter " of sorts which can prove useful.

groceries.forEach((groceryItem, index) => {
  console.log(index, groceryItem);
  console.log(`${index}. ${groceryItem}`);
});
2 Likes