Categories
Featured Development Resources HTML/Javascript

JavaScript forEach Tutorial

The forEach loop was added in JavaScript ES5 to provide a cleaner syntax for looping through iterables in JS.

The most common task to use the for Each method for is to loop through an array. The function passed to the forEach method will be executed on every element of the array, and the first parameter for the function is each item in the array.

arr = [1,2,3,4,5]
arr.forEach(item => console.log(item))
// 1
// 2
// 3
// 4
// 5

JavaScript forEach With Index

With the forEach you can easily get the index each time the passed in function executes by adding a second parameter to the function which will contain the index number.

arr = [1,2,3,4,5]
arr.forEach((item, index) => console.log(item, index))
// 1 0
// 2 1
// 3 2
// 4 3
// 5 4

JavaScript forEach Key In Object

When you use forEach on a object each key and value is passed to the function as an array.

obj = {
    'first': 1,
    'second': 2,
    'third': 3
}
Object.entries(obj).forEach((item) => console.log(item))
// ['first', 1]
// ['second', 2]
// ['third', 3]

JavaScript forEach Break

Breaking a forEach is not easy without changing the elements within the array (you could remove elements so there are no more to loop through and the loop will end), but it is possible by throwing an exception.

arr = [1, 2, 3, 4, 5]
arr.forEach(item => {
    if (item > 3)
        throw 'break'
    console.log(item)
})
// 1
// 2
// 3
// Break exception executed, you'll need to catch it 
// within a try except block just sue for of

You could of course use another loop that can actually break such as as a for…of loop.

arr = [1, 2, 3, 4, 5]
for (item of arr) {
    if (item > 3)
    break
    console.log(item)
}
// 1
// 2
// 3

Javascript forEach Async

The forEach loop will always execute synchronously.

You can try to pass in an async function, but you will get odd behavior as the passed in function will still execute synchronously.

The solution here is to use an async/await compatible solution such as promise.all().

When To Use forEach

It’s best to never use the forEach loop if possible unless you are stuck with ES5 as the for…of loop was added in ES6.

Even then you might want to consider using the traditional for loop which performs better, at best with forEach all you’re doing is saving a few lines of code.