When working with JavaScript arrays, two of the most commonly used methods are forEach and map. Understanding how they work under the hood can help you write cleaner, more efficient code.
JavaScript forEach Method
The forEach method in JavaScript allows you to iterate over an array and run a callback function for each element. It is ideal for performing side effects, such as logging values or updating the DOM.
Custom implementation of forEach:
function myForEach(array, callback) {
for (let i = 0; i < array.length; i++) {
callback(array[i], i);
}
}
Example usage:
myForEach([1, 2, 3], (value, index) => {
console.log(index, value);
});
Key takeaway: forEach is essentially a loop that executes a function on each element of the array. It does not return a new array.
JavaScript map Method
The map method also iterates over an array but differs because it creates a new array from the return values of the callback function. Use map when you want to transform data.
Custom implementation of map:
function myMap(array, callback) {
const result = [];
for (let i = 0; i < array.length; i++) {
result.push(callback(array[i], i));
}
return result;
}
Example usage:
const doubled = myMap([1, 2, 3], x => x * 2);
console.log(doubled); // [2, 4, 6]
Key takeaway: map is a loop that collects transformed values into a new array, unlike forEach, which does not return anything.
Differences Between forEach and map
Featureunknown nodeforEachunknown nodemap
Returnsunknown nodeundefinedunknown nodeNew array
Purposeunknown nodePerform side effectsunknown nodeTransform array elements
Use caseunknown nodeLogging, DOM updatesunknown nodeData transformation
Under the hood: both methods are simple loops that execute a callback function for each element in the array.
Terms & Conditions
|
Privacy Policy
© 2025 minimalsoft. All rights reserved.