javascriptforeach

Making my own ForEach() javascript - element is not defined


I am making my own implementation of forEach in javascript, with the sole purpose of understanding the language better. To be more specific the temporary goal is to understand callbacks better.

This is how far I got until I got stuck.

function myForEach(array, callback) {
  for (let i = 0; i < this.length; i++) {
    callback(array[i]);
  }
}

function callback(element) {
  console.log(element); //insert logic
}

const array = [2, 4, 6, 8, 10];
arr.myForEach(array, callback(element));

I get the following error when running in node:

ReferenceError: element is not defined
    at Object.<anonymous> (C:\Users\Jonas\Desktop\FLEXBOX\test.js:54:31)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Function.Module.runMain (module.js:694:10)
    at startup (bootstrap_node.js:204:16)
    at bootstrap_node.js:625:3

I suspect it is because when the function is called, the element given as parameter in the callback function is not created. Which makes sense, but the real forEach loop when called does not pass in a value created yet?

arr.forEach((element /*does not exist yet?*/) => {
    console.log(element);
});

I have tried invoking the method with a lambda as well, which does not get a correct result either. But a different error

arr.myForEach(array, (element) => {
    console.log(element);
});

then it gives the error:

TypeError: arr.myForEach is not a function
    at Object.<anonymous> (C:\Users\Jonas\Desktop\FLEXBOX\test.js:58:5)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Function.Module.runMain (module.js:694:10)
    at startup (bootstrap_node.js:204:16)
    at bootstrap_node.js:625:3

Solution

  • You have several errors, check this:

    function myForEach(array, callback) {
        for (let i = 0; i < array.length; i++) { 
            callback(array[i]);
        }
    }
    
    function callback(element) {
        console.log(element); //insert logic
    }
    
    const array = [2, 4, 6, 8, 10];
    myForEach(array, callback); 

    The errors are (see comments):

    function myForEach(array, callback) {
      for (let i = 0; i < this.length; i++) { // what is this? You need array.length
        callback(array[i]);
      }
    }
    
    function callback(element) {
      console.log(element); //insert logic
    }
    
    const array = [2, 4, 6, 8, 10];
    arr.myForEach(array, callback(element)); 
    // arr.myForEach is not possible, because myForEach is not a method of JS arrays 
    // callback(element) this invokes a function, you just need to pass it like callback (without parentheses)