Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login

You must be logged to download. Click here to login


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

ECMAScript Array Methods

In this article we will take a deeper look on functions of ECMAScript Array Methods.


ECMAScript provides nine new methods for filtering, iterating, mapping, testing, searching and reducing the arrays. It is important to understand some of generalized terms about these ECMAScript methods before we define them in detail. In most of the methods, a function is passed as their first argument and this function is invoked for some or each elements of the array. In the case of a sparse array, this function will not invoked for non-existent value of the array. In general, three arguments are needed to invoke this function: the array element’s index, value of the array element and the array itself. Often, only the value of the array element is needed to invoke the function and the other two values can be ignored. Optionally, most of the methods can accept a second argument also. Most important property of ECMAScript method’s is that none can modify the original array on which they are invoked but the function, passed as an argument in these methods, can modify the arrays. Now, we are going to take a deeper look on these functions.


The foreach() method invokes a function specified for each element while iterating through an array. This function is passed as the first argument of the foreach() method. Then, foreach() uses the value and index of the array element and the array itself as three arguments to invoke the function. If there is no need for other two parameters than the value, then the function cab be written to pass only one argument, the other arguments will be ignored:

Listing 1: Representing the examples of foreach() method

var data= [1,2,3,4,5]; 						 // Array declaration
// Calculate the sum of the array elements
var sum = 0; 							 // Start at 0
data.forEach(function(value) { sum += value; }); 		// Add each value to sum
sum 								 // => 15
// Now increment each element of the array
data.forEach(function(v, i, a) { a[i] = v + 1; });
data								 // => [2,3,4,5,6]

In this method, the iteration will only stop after all elements have been passed to the function. To terminate early, you have to use a try block to through an exception. In the following code, we use try block in such a way that if the function passed to foreach() throws foreach.break, the loop will exit early:

function foreach(x,y,z) {
try { x.forEach(y,z); }
catch(e) {
if (e === foreach.break) return; 
else throw e;
foreach.break = new Error("Iteration is terminated");


map() method when invoked, passes each of the array element to the user specified function and then it return an array which contains the values returned by the function. For example:

Listing 2: Representing the examples of map() method

x = [2, 4, 6];
y = { return a*a; }); 			// b is [4, 16, 36]

Note that the function. Passed in the map() is invoked in the same way as foreach().The function used in map() is returning a new array of squares, not modifying the original array. The resultant array will be sparse also if the original was, will have the same missing elements and length.


If we want to generate an array containing a subset of the elements of an array, then we use filter() method. You should pass a predicate function in it: a predicate function is the function which returns true or false. This function decides the elements of the subset by checking the return value. If the function returns a true value or a value that converts to true, than the element passed to the function is added to the subset array:

Listing 3: Representing the examples of filter() method

x = [5, 4, 3, 2, 1];
exp1 = x.filter(function(a) { return a < 3 });		 // [2, 1]
exp2= x.filter(function(a,i) { return i%2==0 });	 // [5, 3, 1]

If the array is sparse, then to remove undefined and null elements and close gaps, we can use filters like given below:

x = x.filter(function(a) { return a !== undefined && a != null; });

every() and some()

These two methods are also array predicates: they return a value of either true or false by applying a predicate function to the elements of an array.

The every() method returns true if an only if when the value returned by the predicate function is true for all elements of the array:

Listing 4: Representing the examples of every() and some() methods

x = [1,2,3,4,5];
x.every(function(a) { return a < 8; }) 			//  true: all values < 10.
x.every(function(a) { return a % 2 === 0; }) 		//  false: not all values even.

The some() methods work a little bit different: if the array has at least one element for which the value returned by the predicate function is true, then some() will return a true value and if false value is returned by predicate function for all elements, then only some() will return a false value:

x = [1,2,3,4,5];
x.some(function(a) { return a%2===0; })	 //true x holds some even numbers.
x.some(isNaN) 				//false: x holds no non-numbers

Both of these methods will stop iterations as soon as they will find a return value. Some() will iterates through entire array unless the predicate will return a true value. The every does just opposite, it iterates through the entire array until it get a false value by the predicate function for an array element.

reduce(), reduceRight()

These two methods are used to produce a single value, by combining the elements of an array, using the function specified by user. These operations are also known as “inject” and “fold” and are common operation in functional programing. To explain this, an simple example code is given below:

Listing 5: Representing the examples of reduce() and reduceRight() methods

var x = [1,2,3,4,5]
var addition = x.reduce(function(a, b) { return a+b }, 0); 		// Sum of elements
var mul = a.reduce(function(a, b) { return a*b }, 1); 		// Product of elements
var max_val = a.reduce(function(a, b) { return (a>b)?a:b; });	//Largest elements

Two arguments can be passed into the reduce() method. The first argument is a function that performs an reduction operation. This function is responsible for returning a new value, generated by reducing or combining the actual values of the array. In the above example, the function performs addition, multiplication and fining the largest operations on the elements of the array and then returns the reduced value. The second argument is optional and can be an initial value to pass to the function.

The reduce() method works slightly different than the previously discussed methods such as foreach() and map(). The function used in reduce() method, will pass an initial value, defined as a second argument of reduce(), as its first argument, in its first call. The value, index and array values will work as second, third and fourth argument to that function. After that, from second call, the first argument is replaced by the accumulated result of the reduction so far and then so on.

indexOf() and lastIndexOf()

These two methods are used o found the index value of an given element of the array, if no element is found than they return a -1. indexOf() method is used to search the element from beginning to end of the array, and lastIndexOf() method searches from end to beginning.

Listing 6: Representing the examples of indexOf() and lastIndexOf() methods

x = [0,1,2,1,0];
x.indexOf(1)			 // 1: x[1] is 1
x.lastIndexOf(1) 		//  3: x[3] is 1
x.indexOf(3) 			//  -1: no element has value 3

These methods are different in nature with other methods that they do not accept functions as arguments. They take the value as the first argument whose value they have to search and an optional second argument can be an array index at which to begin the search. If a negative value is passed to the second argument and they are treated as an offset from the end of the array. Another example code is given below:


Arrays play an important role in JavaScript. They support various array operations defined in JavaScript. Except those general methods, ECMAScript also provides some important method, we have discussed here. These methods provide the liberty to the developer to focus himself on other important tasks and let the methods do all other operations on arrays.

Have total 6+ years of experience in developing enterprise applications using DOT.NET 3.5 and 4.0(C#, VB.NET, ADO.NET, ASP.NET),java, JQuery, JSON, LINQ,WCF, MVC3, MVC4, Silverlight, SQL Server, mobile applications and Oracle etc ...

What did you think of this post?
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!

> More info about MrBool Credits
You must be logged to download.

Click here to login