I had a quick question about the .forEach function.
In this scenario below. How did the console know that the function fruits is now called fruit singular? I am understanding the code I used but not the logic behind the computer understanding as I never declared fruit as its own function other than me knowing I want the console to call the individual fruits in my array.
fruits is the name of array. fruit is the name given to the iteration variable. They are not the same thing. What’s more, they are in different scope, the array being global, the iteration variable being local to the callback function.
.forEach() is an iterator that acts upon the array in context (before the dot), iterating over each value in the array one at a time and performing the prescribed action upon that value.
I think I understand… but I also wonder could I have passed:
fruits.forEach(item => console.log(etc) or whichever parameter we are defining related to the const variable array?
Would the iteration variable be named whatever is relavent to the situation of the global scope? I understand that inside of the Array is each individual name of the fruits… but the variable was never defined as a fruit… so it caught me off guard.
would it be equivalent to this?
const robots = [‘R2D2’, ‘C3P0’, ‘BB8’];
robots.forEach(robot => console.log(‘We serve the jedi!’)
Essentially, yes. In other words it does not matter what we name the iteration variable (the parameter of the callback function). Often you see me use x since to me that represents a value, and is adequate enough for me understand the code in a year’s time.