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
element
is only defined insidecallback
. You should instead just be passingcallback
as a function reference. – Natika