Functional Programming - Implement map on a Prototype. Solution causes a typeerror with the this keyword

I have written this code as a solution to the problem but it causes this error.
TypeError: _this is undefined

// The global variable
const s = [23, 65, 98, 5];

Array.prototype.myMap = (callback) => {
const newArray = [];
for(let i = 0; i < this.length; i++){
  newArray.push(callback(this[i]))
}
return newArray;
};

const new_s = s.myMap((item) => item * 2);
  **Your browser information:**

User Agent is: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:104.0) Gecko/20100101 Firefox/104.0

Challenge: Functional Programming - Implement map on a Prototype

Link to the challenge:

Should be

Array.prototype.myMap = function (callback) {

Arrow functions don’t bind this, so attempting to access it in an arrow function is going to error.

Eg this.length – this is undefined (or is whatever this happens to be in the scope you run your function), so it probably doesn’t have a length.

Arrow functions aren’t just “the new way of writing functions”, they’re a syntax for anonymous functions and they work slightly differently, they aren’t a 1-to-1 replacement. In this case you want a function defined using the function keyword because you need it to have its own this context.


Edit: Compare with when you call your method, for example:

[1,2,3].myMap((num) => num * 2)

The callback is an arrow function, that’s no problem: it takes a number and returns that number multiplied by 2, no this or anything

3 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.