Implement custom for-each in JavaScript
Custom forEach: A common JavaScript interview question assessing your core JavaScript skills
Table of contents
No headings in the article.
There are essentially two approaches to implementing a custom forEach
function in JavaScript.
The Primary Approach:
In this fundamental approach, we create a function that accepts two parameters: an array and a callback function. Within this function, we employ a straightforward for
loop to iterate through each element within the array. For each element, we invoke the callback function, passing three arguments: the current item, its index within the array, and the array itself.
Here's an example usage of this approach:
Stay tuned for the Advanced Approach! We'll delve into this exciting topic in our upcoming article !!!!
function customForEach(arr, callback) {
for (let i = 0; i < arr.length; i++) {
callback(arr[i], i, arr);
}
}
// Example usage:
const numbers = [1, 2, 3, 4, 5];
customForEach(numbers, (item, index, array) => {
console.log(`Item: ${item}, Index: ${index}, Array: [${array}]`);
});