The forEach method in JavaScript
Details, examples, practice
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.
array.forEach(function(element, index, array) {
// operation
});
Parameters
const numbers = [1, 2, 3];
numbers.forEach(function(num) {
console.log(num);
});
Result:
1
2
3
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.
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.
arr.forEach(async (item) => {
await doSomething(item); // this will not wait
});
const users = [
{ name: 'Anna' },
{ name: 'David' },
{ name: 'Narek' },
];
users.forEach(user => {
console.log(`Hello, ${user.name}!`);
});
Result:
Hello, Anna!
Hello, David!
Hello, Narek!
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.
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
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.