Array. prototype. forEach()
Calls a function for every element of the array.
- Returns
undefined- Changes the original
- No
Example
#const modules = ['HTML', 'CSS', 'JavaScript']
modules.forEach((module, index) => {
console.log(`${index + 1}. ${module}`)
})Definition and usage
#The forEach() method walks through the array’s elements in order and calls the given function for each one. It doesn’t return a value (always undefined), so it’s used for side effects: logging, saving, adding elements to the page.
A forEach() loop can’t be stopped with break. If you want to exit early, use a plain for...of loop or the some() or find() methods.
It doesn’t play well with await either: async functions inside forEach() aren’t waited for one after another. For sequential async operations, a for...of loop is a better fit.
Syntax
#array.forEach(callbackFn)
array.forEach(callbackFn, thisArg)Parameters
#callbackFn
function (element, index, array)
The function called for every element.thisArg
optional
Thethisvalue inside the function.
More examples
#const result = [1, 2, 3].forEach((n) => n * 2)
console.log(result)Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- If you’re building a new array from the results, use
map()instead offorEach()withpush(). - For loops with
await, and for loops you need to break out of, choosefor...of.
Related entries
#- map() vs forEach()map() builds a new array from a function’s results, while forEach() only calls the function for every element and always returns undefined.
- Array.prototype.map()Creates a new array with the results of calling a function for every element.
- for...ofWalks the successive values of an iterable object: an array, a string, a Map, a Set, and others.
- Array.prototype.some()Checks whether at least one element matches a condition.
- Array.prototype.reduce()Reduces the whole array to a single value, such as a sum, an object, or a new array.
Spotted a mistake or missing an example? Write to us.