Hone logo
Hone
Problems

Implementing Array.prototype.forEach in JavaScript

The forEach method is a fundamental array method in JavaScript that allows you to iterate over each element in an array and execute a provided function once for each element. Replicating this functionality from scratch is a great exercise in understanding how array methods work under the hood and reinforces core JavaScript concepts like closures and higher-order functions. This challenge asks you to implement a custom forEach method for the Array.prototype.

Problem Description

Your task is to implement a forEach method directly on the Array.prototype. This method should accept a single argument: a callback function. This callback function will be executed for each element in the array. The callback function should receive three arguments:

  • currentValue: The value of the current element being processed in the array.
  • index: The index of the current element being processed in the array.
  • array: The array that forEach was called upon.

The forEach method should not return a value; it should simply iterate over the array and execute the callback function for each element. It should handle empty arrays gracefully and should not modify the original array.

Key Requirements:

  • The implementation must be added directly to Array.prototype.
  • The callback function must be executed for each element in the array, in ascending index order.
  • The callback function must be invoked with the correct arguments (currentValue, index, array).
  • The method should not return any value (implicitly return undefined).
  • The original array should not be modified.

Expected Behavior:

When forEach is called on an array, the provided callback function should be executed for each element in the array. The callback function should receive the element's value, index, and the array itself as arguments.

Edge Cases to Consider:

  • Empty Array: The forEach method should not throw an error or do anything if the array is empty. The callback function should simply not be executed.
  • this context: While not strictly required for this basic implementation, consider how the this context within the callback function might be handled in more advanced scenarios. For this challenge, the default this value (undefined in strict mode, the global object in non-strict mode) is acceptable.
  • Callback not a function: If the provided argument is not a function, the forEach method should do nothing and not throw an error.

Examples

Example 1:

Input: const arr = [1, 2, 3];
       arr.forEach(function(element) {
         console.log(element * 2);
       });
Output: 2
       4
       6
Explanation: The callback function is executed for each element in the array.  The element's value is multiplied by 2 and logged to the console.

Example 2:

Input: const arr = [];
       arr.forEach(function(element) {
         console.log(element);
       });
Output: (No output)
Explanation: The array is empty, so the callback function is never executed.

Example 3:

Input: const arr = [10, 20, 30];
       let sum = 0;
       arr.forEach((num, index) => {
         sum += num;
         console.log(`Adding ${num} at index ${index}`);
       });
Output: Adding 10 at index 0
       Adding 20 at index 1
       Adding 30 at index 2
Explanation: The callback function receives the element's value and index. The sum is calculated and logged to the console.

Constraints

  • The implementation must be valid JavaScript code that runs in a standard JavaScript environment (e.g., a web browser or Node.js).
  • The solution should be reasonably efficient. While performance is not the primary focus, avoid unnecessarily complex or inefficient algorithms.
  • The solution must not rely on the built-in Array.prototype.forEach method. The goal is to implement it from scratch.
  • The input array can contain any type of data (numbers, strings, objects, etc.).

Notes

  • Think about how to access the length of the array and iterate through its elements.
  • Consider using a for loop or a while loop to iterate over the array.
  • Remember that the callback function should be executed for each element in the array.
  • This is a good opportunity to practice your understanding of closures and higher-order functions.
  • Pay close attention to the arguments that the callback function should receive.
Loading editor...
javascript