View Single Post
Old 01-05-2013, 02:23 AM   PM User | #14
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,210
Thanks: 59
Thanked 3,996 Times in 3,965 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
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?
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Old Pedant is offline   Reply With Quote
Users who have thanked Old Pedant for this post:
jmrker (01-05-2013)