3

I'm trying to implement native forEach method. Here's my code:

Array.prototype.myEach = function(cb) {
     for(let i=0; i<this.length; i++) {
         cb(this[i], i)
     }
}

If I declare let a = [] (something) and then run [].myEach then it works.

let a = [1,2,3,4,5]; // or even []

[1,2,3,4,5].myEach(function(val, i){
    console.log(val); //works
});

But if I don't declare the array on the top, it's not even recognizing the prototype.

[1,2,3,4,5].myEach(function(val, i){ //fails
    console.log(val);
});

Problem:

If I remove let a = [1,2,3,4,5], doing [1,2,3,4].forEach fails.

I'm not able to understand why.

TechnoCorner
  • 4,879
  • 10
  • 43
  • 81
  • I'm not overwriting it. I'm creating my own ForEach (myEach) to learn native methods. – TechnoCorner Mar 23 '18 at 04:45
  • 3
    You need a semicolon after your assignment statement to `Array.prototype.myEach`. Otherwise it parses the brackets as accessing a property of the function you're assigning. – 4castle Mar 23 '18 at 04:45
  • 1
    related: https://stackoverflow.com/q/46965567/1048572 – Bergi Mar 23 '18 at 04:56

1 Answers1

4

Include a semi-colon after the myEach function:

Array.prototype.myEach = function(cb) {
     for(let i=0; i<this.length; i++) {
         cb(this[i], i)
     }
};

[1,2,3,4,5].myEach(function(val, i){ 
    console.log(val);
});

Without the semi-colon, this parses like this:

Array.prototype.myEach = function(cb) {
     for(let i=0; i<this.length; i++) {
         cb(this[i], i)
     }
}[1,2,3,4,5].myEach( ....etc

and [1,2,3,4,5] attempts to obtain property 5 from the function (object) - as if you had written function(){}[5]. There is no property 5 and so this is undefined and attempting to call myEach on undefined gives an error.

The original worked because the intermediate let statement achieved the separation (thanks to the semi-colon but irrelevant of the actual let a = statement).

andrew
  • 1,723
  • 2
  • 12
  • 24