The forEach Method in JavaScript
When working with arrays in JavaScript, we often need to perform some operation on each element. For this, there is a very convenient method: forEach(). Despite its simplicity, it is a powerful tool for writing concise and readable code.
In this article, we will not only explore how forEach works but also create our own version from scratch. Yes, there’s no magic—everything is just simple functions.
Syntax
array.forEach(function(element, index, array) {
// operation
});
Parameters
- element – the current element
- index – the index of the current element
- array – the entire array (optional to use)
Simple Example
const numbers = [1, 2, 3];
numbers.forEach(function(num) {
console.log(num);
});
Result:
1
2
3
What Does forEach Return?
const result = [1, 2, 3].forEach(n => console.log(n));
console.log(result); // undefined
forEach does not return anything. It simply performs an operation for each element.
Difference from a for Loop
const arr = ['a', 'b', 'c'];
// for
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
// forEach
arr.forEach(item => {
console.log(item);
});
forEach is more readable but does not support break, continue, or return to exit the loop.
Special Considerations
- Cannot be stopped or exited, unlike a for loop.
- Does not await async/await – If you need to await, use for...of:
arr.forEach(async (item) => {
await doSomething(item); // this will not wait
});
Real-World Example
const users = [
{ name: 'Anna' },
{ name: 'David' },
{ name: 'Narek' },
];
users.forEach(user => {
console.log(`Hello, ${user.name}!`);
});
Result:
Hello, Anna!
Hello, David!
Hello, Narek!
How forEach Works Internally
When you write:
[1, 2, 3].forEach(fn);
It is the same as writing:
Array.prototype.forEach.call([1, 2, 3], fn);
In other words, forEach is just a function attached to Array.prototype. We can also write our own version. Here's how.
Let’s Write Our Own myForEach Function
function myForEach(array, callback) {
for (let i = 0; i < array.length; i++) {
callback(array[i], i, array);
}
}
Usage:
const numbers = [10, 20, 30];
myForEach(numbers, function(num, index) {
console.log(`Index ${index}: value ${num}`);
});
Result:
Index 0: value 10
Index 1: value 20
Index 2: value 30
We Can Add Our Function to the Array
For educational purposes, we can add our method to Array.prototype.
Array.prototype.myForEach = function(callback) {
for (let i = 0; i < this.length; i++) {
callback(this[i], i, this);
}
};
Usage:
['apple', 'banana'].myForEach((item, i) => {
console.log(`${i}: ${item}`);
});
Result:
0: apple
1: banana
It is not recommended to modify built-in prototypes in production code, as it may cause issues.