Part of a Javascript course that I'm taking, you're supposed to create your own forEach function that takes two arguments, an array and a callback. It's supposed to pass to the callback each element, its index, and the array itself. Should return undefined. Here is mine:
function myForEach (arr, cb) {
for(var i = 0; i < arr.length; i++) {
var elem = arr[i];
cb(elem, i, arr);
}
}
Then, you're supposed to reference it in another function and use that to execute some example functions. Particularly, you're supposed to write a function that accepts an array and a callback as arguments and it should pass the callback to every element, its corresponding index, and the array itself. And then it should return a new array where each element in the new array is the return value of the callback. Here is the function in question:
function myMap(arr, cb) {
var mapped = [];
mapped.push(myForEach(arr, cb));
return mapped;
}
I don't understand why (in this example), I'm getting undefined as my value, when the callback being passed should be returning a value:
console.log(myMap([1, 2, 3], function(ele, i, arr){
return ele * i;
}));
// [0, 2, 6] expected return value
Generally just a bit confused here on balancing what's returning undefined vs. what isn't, and how to actually push a value from the callback into my empty array.
return undefinedfunction myMap(arr, cb) { var mapped = []; myForEach(arr, function(ele, i, arr) { mapped.push(cb(ele, i, arr)); }); return mapped; }