1. Computing & Technology

Analysing Array.forEach

From , former About.com Guide

forEach is a recent addition to the methods available for processing JavaScript arrays. Its purpose is to run a specified function once for each element of the array.

At the time of it being introduced only gecko based browsers such as Firefox supported it. To make it really easy to actually use it the people who added it into Firefox also posted a copy of JavaScript equivalent code so that you can implement the method for all browsers by adding this code to your script. Their script uses a few aspects of JavaScript that you do not see used all that often and so an analysis of just what their script does will show how to use a few JavaScript commands that you may not have seen before.

Note that you can pass one or two parameters into forEach. The first is the function to be called for each element in the array and the second optional parameter is the object that this will refer to within the function. The function that you call cant accept up to three parameters containing the element from the array, the index of that element within the array, and the array itself.

We'll start by looking at the complete code.



if (!Array.prototype.forEach)
{
Array.prototype.forEach = function(fun /*, thisp*/)
{
var len = this.length >>> 0;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
fun.call(thisp, this[i], i, this);
}
};
}

So that's the code to add into your script to add support for the forEach() method on arrays where the method isn't supported directly by the browser. Now let's examine what it does.


if (!Array.prototype.forEach)

This statement tests if the browser natively supports forEach. If it does then there is no need to run any of the added code since the native version will run faster than the version written in JavaScript and give the same result.


Array.prototype.forEach = function(fun /*, thisp*/)

This is the line that actually defines the new method on all arrays by adding it to the Array.prototype. The commented second argument is the way the people at Mozilla who wrote this code remind themselves that there is an optional second argument to the method and what variable name they are going to load it into.


var len = this.length >>> 0;

This statement copies the length property of the array into a separate variable called len in order to make it faster to access. Using the zero fill right shift bit operator to move the bits in the length zero bits to the right and zero fill is just a fancy shortcut for making the length zero if it is not defined.


if (typeof fun != "function")

This tests the type of object passed to the first argument to test whether it is a function or not.


throw new TypeError();

This statement causes the script to throw an error if fun doesn't contain a function. The error it throws is one of the JavaScript supplied messages, in this case the one that indicates that there is something wrong with a field type.


var thisp = arguments[1];

This is the statement that reads in that optional second argument that was commented out at the top of the script. You would achieve exactly the same result by deleting this line and uncommenting the argument in the method definition but then you wouldn't have anything to remind you that it is optional.


for (var i = 0; i < len; i++)

Here is the start of the loop where we are going to process across all of the actual entries in the array. Note that we can't use a for..in loop in place of this because it would pick up any methods we have added to the array as well as the actual array contents (including this forEach method).


if (i in this)

A JavaScript array need not have contiguous values. If all we define in our array are elements [3] and [7] then the array length is eight and the number of actual elements in the array is two. This if statement checks that an element actually exists at the current location within the array that we have reached in processing through the loop prior to our trying to do anything with it. With the example array this would evaluate as false for i equal to 0,1,2,4,5,6 and true for i equal 3 and 7.


fun.call(thisp, this[i], i, this);

Finally we get to the statement that actually performs the forEach processing. This statement actually calls our function. The reason that we need to call the function this way is that the function name itself is variable depending on what function was passed into the method. The call method on a function allows is to call a function without needing to know its name.

The thisp value (our optional second parameter to the forEach call) identifies the object that the processing is to be performed on. If it isn't supplied then the processing will run against the global Object. The second through fourth parameters in this call are passed into the first three arguments of the function being called and contain the current element within the array, the index of the current element within the array, and the array itself.

©2012 About.com. All rights reserved.

A part of The New York Times Company.