I'm trying to create a forEach() function that takes an array and a function, then performs the function action on each element of the array. However, when trying to pass the below anonymous function, I get undefined. I tried adding a return to the forEach() function after reading some other posts but then the function doesn't run at all and just returns the first array[i] it receives without modifying it.
function forEach(array, action){
for(var i = 0; i < array.length; i++)
action(array[i]);
}
var myArray = [1, 2, 3];
var something = forEach(myArray, function(element){return element++;});
console.log(something)
//undefined
That returns undefined.
function forEach(array, action){
for(var i = 0; i < array.length; i++)
return action(array[i]);
}
var myArray = [1, 2, 3];
var something = forEach(myArray, function(element){return element++;});
console.log(something)
//undefined
That returns 1.
What am I missing?
(I am aware a .forEach() function exists, I am trying this as a learning exercise)
returnstatement. Second one has a loop that exits on first iteration. It's a strange learning exercise anyway.