JavaScript forEach()
going through each element in an array
Last updated
going through each element in an array
Last updated
Suppose we have an array and we wish to iterate through each of its elements:
We could use a for
loop as we saw in the page, or we could use a cleaner, high-order forEach
method like such:
Take note of the inner curly braces {}
and the outer brackets ()
in forEach
!
We call the function inside the forEach
method, a callback function, as it calls itself back when we call forEach
!
We do not need to write any code to determine our position in the array; JavaScript takes care of this!
In addition to the current element of the iteration, the forEach
method also has two optional parameters:
the index
of the current element
the original array
showing all the elements
For example, we could provide more detail to the message logged to the console:
Logging only the original grades in the first iteration with that if
statement, this will log:
Remember that forEach()
:
always returns undefined
iterates through each element in the array and calls other functions to output a result
does not modify the original array
does not create a new array
other than throwing an exception, we cannot break out of a forEach
We need now only focus on what we want to do with each element