I know this is a stupid question but im not understanding why
fruits.forEach(fruit => console.log(`I want to eat a ${fruit}.`))
within the bracket the function is ‘fruit’ and not ‘fruits’
?
I dont understand how the callback function in the .forEach method array works either, if that could be explained it would be really helpful.
3
Answers
let use break it down so as to understand it better
here we have a list of fruits , and we are iterating/looping over it and performing some action on each of the items in it.
as you notice we are using a lambda function which does something on each of the list items
this function is independent of the loop construct. It just does something with a given item which is a single fruit in your case
The forEach() method is an iterative method. It calls a provided callbackFn function once for each element in an array in ascending-index order. Unlike map(), forEach() always returns undefined and is not chainable. The typical use case is to execute side effects at the end of a chain.
callbackFn is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays.
forEach() does not mutate the array on which it is called, but the function provided as callbackFn can. Note, however, that the length of the array is saved before the first invocation of callbackFn. Therefore:
callbackFn will not visit any elements added beyond the array’s initial length when the call to forEach() began.
Changes to already-visited indexes do not cause callbackFn to be invoked on them again.
If an existing, yet-unvisited element of the array is changed by callbackFn, its value passed to the callbackFn will be the value at the time that element gets visited. Deleted elements are not visited.
for detailed visit: Moz Dev Link
The callback function is an arrow function with a single parameter, which represents the current element of the array during iteration. In this case, each element in the fruits array is a string representing a fruit name, and that’s why the parameter of the callback function is named fruit.
As the forEach method iterates through the fruits array, it calls the callback function for each element, passing the current element (i.e., a fruit name) as an argument to the callback function. Inside the callback function, it uses string interpolation (backticks and ${}) to create a message, which is then logged to the console using console.log().
So, in summary, the callback function is used to specify what action should be performed on each element of the array during iteration, and the parameter of the callback function represents the current element being processed. In this case, it’s named fruit because it represents a single fruit name from the fruits array.