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.