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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With