Tell us what’s happening:
Can someone help me understand why this: newArray.push(this.forEach(val => callback(val)));
returns [ undefined ]
but this: this.forEach(val => newArray.push(callback(val)));
returns an array with the correct values?
Your code so far
// the global Array
var s = [23, 65, 98, 5];
Array.prototype.myMap = function(callback){
var newArray = [];
// Add your code below this line
this.forEach(val => newArray.push(callback(val)));
return newArray;
// Add your code above this line
return newArray;
};
var new_s = s.myMap(function(item){
return item * 2;
});
console.log(new_s);
Challenge: Implement map on a Prototype
Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/functional-programming/implement-map-on-a-prototype
The forEach method returns undefined, so in the first example you are adding undefined to the array.
Right, but why does it return undefined? I’m pretty sure it has to do with the ‘this’ but I’m not sure why.
Also I don’t fully understand how exactly ‘this’ works
Because that is the definition of the function:
The forEach function is just a functional replacement for the ‘for’ statement:
for (let i=0; i<arr.length; i++) {
...
}
The for statement doesn’t return a value, it just executes the code inside of the block. forEach does the same thing.
I understand that much. So forEach() returns what the callback returns for each element of the array. Why would (val => callback(val)) return undefined?
forEach() returns ‘undefined’. That’s it, nothing more. It does not care what you do in the function you pass into it. It will always return ‘undefined’.
but would the function that I send to forEach not return the value?
It could, but forEach doesn’t care about that, it always returns ‘undefined’. So any value returned by the function is basically lost.
1 Like
Wow. I appreciate it. I don’t think I would have found that on my own.
As far as your question about ‘this’, you are creating a new method on the Array prototype, so in this case ‘this’ refers to the array you are calling the method on. For example:
const my_arr = [...];
my_array.myMap(callback);
‘this’ refers to my_arr. So
this.forEach(...)
is basically the same thing as
my_arr.forEach(...)