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.

3
  • I'm not overwriting it. I'm creating my own ForEach (myEach) to learn native methods. Commented Mar 23, 2018 at 4: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. Commented Mar 23, 2018 at 4:45
  • 1
    related: stackoverflow.com/q/46965567/1048572 Commented Mar 23, 2018 at 4:56

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

3 Comments

could you explain why?
good work debugging @andrew
My original answer described it as a syntax error but the actual error is that it tries to call myEach on an undefined value. I updated the explanation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.