Maybe if we look at the forEach method it will be clearer. It truly is simple.
First of all, let me simplify it to *require* that the callback function be supplied:
Code:
Array.prototype.forEach = function( callback ) {
// we build the new array here:
var ar = [];
// we loop through every element of the old array:
for ( var i = 0; i < this.length; ++i ) {
// and we put the RESULT of calling the callback function into
// the corresponding element of the new array:
ar[i] = callback( this[i], this, i );
}
// finally returning the new array:
return ar;
}
So the only thing to really need to understand is this line:
Code:
ar[i] = callback( this[i], this, i );
The assignment into the new array is hopefully obvious. So let's look at *HOW* the callback function is called:
Code:
callback(
this[i], /* the *VALUE* of the current (i-th) element of the array */
this, /* the *ENTIRE* current array */
i /* the element number */
);
So you can see that in your callback function:
Code:
// using one of your example:
function(element, array, index)
{
// remember: element is the *VALUE* of array[index]
// but it was *ALREADY* fetched out of the array in the forEach method/function
// so when we do this, we are indeed changing the element number index in the
// original array...
array[index] += 1;
// but that in no way affects the value of element:
return element;
}
Did you perhaps forget that arrays are passed to functions *BY REFERENCE*? So the variable
array in your callback function is 100% the same *OBJECT* as the array referred to by
this in the
forEach method.
Clearer?