views:

89

answers:

2

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.

+3  A: 

The big difference between map and forEach as specified in your question is that forEach operates on the original array elements. You are (potentially) changing each element in the original array. On the other hand, map is running through your array, applying a function to each element, and emitting the result as a new array. The "side effect" is probably meant to be the fact that the original array is being changed.

The fact that there's no database involved (although now there could be, with newer browsers, HTML5, etc.) does not mean that you won't have to operate on data structures. Your array can contain not only numbers, but DOM objects or just about anything else.

Ken Redler
+1  A: 

You can use map as though it were forEach.

It will do more than it has to, however.

scope can be an arbitrary object; it's by no means necessarily this.

As for whether there are real uses for map and forEach, as well to ask if there are real uses for for or while loops.

wombleton
But why is both "scope" and "this" being called here:func.call(scope, this[i], i, this); Isn't scope a parameter that is equal to the current object, which is "this"?
JohnMerlino
No, it *can* be equal to the current object. The object itself is passed as the third parameter to the array. `scope = scope || this` means "if `scope` is falsy (undefined, null, false, etc) set scope to `this` instead and carry on".
wombleton
Can you link me to an example when it's not equal to this?
JohnMerlino
https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/forEach has one under "Printing the contents of an array with an object method"
wombleton