The forEach()
loop was introduced in ES6 (ECMAScript 2015) to execute the given function once for each element in an array in ascending order. The callback function is not invoked for empty array elements.
You can use this method to iterate through arrays and NodeLists in JavaScript.
Looping through arrays using forEach()
Here is the syntax of Array.forEach()
method:
array.forEach(callback(currentVal [, index [, array]])[, thisVal])
The callback function accepts between one and three arguments:
currentVal
— The value of the current element in the loopindex
— The array index of the current elementarray
— The array object theforEach()
loop was called upon
Only the first argument is required. The other two are optional. You can name these variables anything you want. If the thisVal
argument is provided, it will be used as a callback's this
value.
The following example demonstrates how you can use the forEach()
loop to iterate through an array in JavaScript:
const birds = ['🐦', '🦅', '🦆', '🦉']
birds.forEach((item, index) => {
console.log(`${index} : ${item}`)
})
Here is the output:
0 : 🐦
1 : 🦅
2 : 🦆
3 : 🦉
Let us look at another example array that contains empty values:
const partialArray = [2, 4, , 3]
partialArray.forEach(num => console.log(num))
// output
// 2
// 4
// 3
As you can see above, the callback function is skipped for the empty value.
Looping through NodeList
using forEach()
A NodeList
also provides a forEach()
method which is similar to Array.forEach()
, but only works for NodeLists as shown in the following example:
const elems = document.querySelectorAll('div')
elems.forEach((elem, index) => {
console.log(elem) // the elment
console.log(index) // the index in the NodeList
})
Skipping items
In a for
loop, you can skip the current item using the continue
keyword or use break
to stop the loop altogether.
But that is not the case with the forEach()
method. Since it executes a callback function for each element, there is no way to stop or break it other than throwing an exception.
However, you can conditionally check the item value and use the return
statement to skip the current item. For example, if you want to log all birds' names to the console except Owl, you'd do the following:
const birds = ['Eagle', 'Parrot', 'Owl', 'Sparrow']
birds.forEach((item, index) => {
// if `Owl`, skip it
if (item === 'Owl') {
return
}
// otherwise, log the bird's name
console.log(item)
})
Browser compatibility
The Array.forEach()
function works well in all modern browsers, including Internet Explorer 9 and higher. However, you can use a polyfill to make it compatible all the way back to IE6.
The NodeList.forEach()
method is also supported by all the latest browsers except Internet Explorer. You need a polyfill to continue using it in IE.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.