Javascript index

In the Javascript part, in the forEach method, I am confused as to why the index parameter could be written that way. I googled and Google said index was not a keyword, and if I replaced index with i, the result would still be the same.

How does panes[index] point to the element without knowing index is a number or not?

Link here: link

Thank you so much!

The forEach() method is defined as having a 2nd optional argument for its callback function. Really, all the index variable is doing is providing you a means of accessing the index of the current array element from inside the forEach() method’s block scope. It’s defined such that whichever variable you enter as the 2nd argument will become the variable for the index. So i will work. pizza would work too.

Normally when you use forEach without any optional arguments, you can say what you want done with each element, but you can’t customize the logic in a way that depends on which index your are currently on. It is only when you include the index argument that you gain access to it.

const arr = ["bobbb", "hgogogo", "fbuwibfw", "dhsoeb", "sbvhfe"]; arr.forEach((item, pizza, array) => { console.log(item); console.log(pizza); });
1 Like

Thank you!!! It’s much clearer now

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.