what use does the javascript forEach method have (that map can't do)?

Posted by JohnMerlino on Stack Overflow See other posts from Stack Overflow or by JohnMerlino
Published on 2010-06-13T23:58:53Z Indexed on 2010/06/14 1:12 UTC
Read the original article Hit count: 257

Filed under:
|
|
|
|

Hey all,

The only difference I see in map and foreach is that map is returning an array and foreach is not. However, I don't even understand the last line of the foreach method "func.call(scope, this[i], i, this);". For example, isn't "this" and "scope" referring to same object and isn't this[i] and i referring to the current value in the loop?

I noticed on another post someone said "Use forEach when you want to do something on the basis of each element of the list. You might be adding things to the page, for example. Essentially, it's great for when you want "side effects". I don't know what is meant by side effects.

Array.prototype.map = function(fnc) {
var a = new Array(this.length);
for (var i = 0; i < this.length; i++) {
    a[i] = fnc(this[i]);
}
return a;
}

Array.prototype.forEach = function(func, scope) { 
scope = scope || this; 
for (var i = 0, l = this.length; i < l; i++) 
func.call(scope, this[i], i, this); 
} 

Finally, are there any real uses for these methods in javascript (since we aren't updating a database) other than to manipulate numbers like this:

alert([1,2,3,4].map(function(x){ return x + 1})); //this is the only example I ever see of map in javascript.

Thanks for any reply.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about array