Tell us what’s happening:
So i accidentally ran across the solution to this problem i was working
andupon viewing it im left more confused then when i started the assignment Your code so far
Array.prototype.myMap = function(callback) {
const newArray = [];
// Only change code below this line
for (let i = 0; i < this.length; i++) {
newArray.push(callback(this[i], i, this));
}
// Only change code above this line
return newArray;
};
I understand how callbak as a function is being constructed through calling it, but how is “this” an array?
How is callback using this to find an array Your browser information:
User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36
Challenge: Functional Programming - Implement map on a Prototype
this references the array it was called on, in this instance. In the map function, there are 3 parameters you can call on to work with: 1) the element in the current iteration of the array 2) the index of the current iteration and 3) a reference back to the array itself.
Think of map like a for loop and this[i] as being each element in the array as it goes through the loop, i as the current index in the loop, and this being the array itself.
ok and the array value is being inserted into the “this” placeholder… like “off screen”… i just don’t see an example of the array inserting itself into “this” ever… unless im missing something
I see what you’re thinking but it isn’t inserting itself back into the array. We’re calling a callback function that is returning some value and that’s what is passed back into the array. Think of it like you have the boss which is the myMap function, and every loop it passes off some work to the callback function that’s passed in and that callback function returns some value back and adds it to the new array. Then, the new array is returned.
This means that this is the array ["naomi", "quincy", "camperbot"] and each element will be converted to uppercase, passed into the new array and then returned at the end, resulting in:
["NAOMI", "QUINCY", "CAMPERBOT"]
You don’t have to reference the index or the array itself. Consider those as optional parameters. But you do have to reference each individual element as it is the very first parameter which is why it’s this[i] (or each individual element) in that solution as the first parameter.
Yes, exactly! And if you look at the example function, where you’re converting each element to uppercase, element is really just a placeholder variable for this[i]. I hope you see all of this clearer.