1

While implementing map i noticed that in arrow notation there is type error this.forEach is not a function while in case of using es5 function its running fine.

Array.prototype.map = function(projectionFunction) {

 var results = [];

        //Array.foreach is also error

 this.forEach( (arrayItem) => {
  results.push(projectionFunction(arrayItem));
 });

 return results;
};

var res = [5,10,15].map((x) => { return x + 2; });
console.log(res);

Not working

    Array.prototype.map = (projectionFunction) => {
    
     var results = [];
    
     this.forEach( (arrayItem) => {
      results.push(projectionFunction(arrayItem));
     });
    
     return results;
    };
    
    var res = [5,10,15].map((x) => { return x + 2; });
    console.log(res);

Error

this.forEach( (arrayItem) => {
         ^

TypeError: this.forEach is not a function
owais
  • 4,752
  • 5
  • 31
  • 41
  • You cannot use arrow *functions* for *methods*. – Bergi Feb 01 '17 at 02:38
  • @Bergi—well, you *can*, but don't expect *this* to be useful. ;-) – RobG Feb 01 '17 at 02:42
  • @Bergi answer have no explanation even if use Array.forEach instead this.forEach... – owais Feb 01 '17 at 02:53
  • @owaishanif786 Have you read the answer to the canonical question? `forEach` has nothing to do with that (and there's no `Array.forEach` function, so that wouldn't work anyway). – Bergi Feb 01 '17 at 02:57
  • @owaishanif786—arrow functions adopt the *this* of their containing scope. Since this appears to be global code, then in the arrow function *this* is the global object, not the object on which the method was called (it can't be set at all by the call, it's set lexically). It's all in the answer referenced by Bergi. – RobG Feb 01 '17 at 04:33

0 Answers0