Javascript Array Foreach Method Example

Getting Started

forEach() calls a provided callback function once for each element in an array in ascending order.
the callback function will be called only for elements of the array that exist.

The callback function takes three arguments.
1. The value of the element.
2. The index of the element.
3. The object being traversed.

Syntax

arr.forEach(function callback(currentValue [, index[, array]]) {
	// iterator
}[, thisArg]);

Example 1

var arr = ['abc', 'cde', 'fgh'];
arr.forEach(function(value, index) {
	console.log('Index: ' + index + ' value: ' + value)
});

Output:

// Index: 0 value: abc
// Index: 1 value: cde
// Index: 2 value: fgh

Example 2

If you pass thisArg then it will be used as this value when executing callback.

var arr = ['abc', 'cde', 'fgh'];
arr.forEach(function(value, index) {
	console.log('Index: ' + index + ' value: ' + value)
	console.log(this);
}, arr);

Output:

// Index: 0 value: abc
// (3) ["abc", "cde", "fgh"]
// Index: 1 value: cde
// (3) ["abc", "cde", "fgh"]
// Index: 2 value: fgh
// (3) ["abc", "cde", "fgh"]