Tadeusz Łazurski Tadeusz Łazurski - 3 months ago 15
Javascript Question

Array.prototype.each = function(callback) { for (var i = 0; i < this.length; i++) callback(this[i]); } - is this ok?

I know it's a matter of taste, but for my taste using for loop each time I want to iterate over array is bad. So I came up with this:

Array.prototype.each = function(callback) {
for (var i = 0; i < this.length; i++)
callback(this[i]);
}


Now I can do:

[10, 20, 30].each(function(n) { console.log(n/10) })


Later I found some tips on the Internet that suggested this approach, but I still wonder if it's free from side effects. It seems very obvious, and that is what worries me :)

I'm not using any library like jQuery or Prototype. I'm coding for Node.js.

Answer

This does have a pretty big side effect

If we now run the following code

a = [10, 20, 30];
for (var i in a) {
    console.log(i + ": " + a[i]);
}

And check the console output, we see this:

0: 10
1: 20
2: 30
each: function (callback) {
  for (var i = 0; i < this.length; i++)
    callback(this[i]);
}

Which restricts the type of for loop you can do on an array to

a = [10, 20, 30];
for (var i = 0; i < a.length; ++i) {
    console.log(a[i] + ": " + a[i]);
}