Array forEach() Method

The JavaScript Array forEach() method executes a callback function for each element in an array. The callback function takes three parameters: the value of the array element, its numeric index and the array containing the element itself. The syntax is as follows


			array.forEach(callback(value,index,arr), thisValue)
			

The three parameters of the callback() function are as follows

value
Optional. The value of the array element.
index
Optional. Index of the current element in the array.
arr
Optional. The array where the current element belongs.

The second parameter thisValue is the value to be used as this in the callback function.

In the example below, for each element in the array named os, the forEach() method executes the callback function.


			var os = ["Debian", "Fedora", "openSUSE", "Ubuntu"];

			os.forEach(function(value,index,arr){
				console.log("Value: " + value + ", Index: " + index);
			});
			

and it prints the following messages into the console


			Value: Debian, Index: 0
			Value: Fedora, Index: 1
			Value: openSUSE, Index: 2
			Value: Ubuntu, Index: 3
			

The thisValue Parameter

We can pass a value into the anonymous callback function which can then be used as this inside it. Here we make use of the same array defined above and pass an array ['Gentoo'] containing just a single element to the .forEach() method, which is then used as this inside the anonymous callback function.

The this keyword will contain the passed array ['Gentoo'] and hence this[0] will give its first element 'Gentoo'


				var os = ["Debian", "Fedora", "openSUSE", "Ubuntu"];

				os.forEach(function(value,index,arr) {
				    console.log(this);
				    if(value !== this[0]) {
				        console.log(value + ' != ' + this[0]);
				    }            
				}, ['Gentoo']);
				

The parameters value, index, arr to be passed to the callback function are all optional. And besides arrays, numbers and strings can also be passed as arguments to the thisValue parameter.