Understanding The forEach Method for Arrays in JavaScript

Improve your iteration

Photo by Mika Baumeister on Unsplash

What is forEach?

The forEach method executes the callback function against all element of the array.

forEach method in JavaScript

Syntax

array.forEach(callbackFunction, [, thisArg]);// thisArg is optionalarguments for callbackFunctioncallbackFunction(currentValue, index ,array) {   //index, array is optional}

The forEach method doesn’t return anything.

Let’s start basic with a loop, then convert that into a forEach loop

var array = [1,2,3,4,5];function print(val, index) {    console.log(`array[${index}\] = ${val}`);}for(let index =0, len = array.length; index < len; index++ ) {       let val = array[index];
print(index, val);
}

Now, let’s do the same operation using a forEach loop.

var array = [1,2,3,4,5];function print(val, index) {   console.log(`array[${index}] = ${val}`);}array.forEach(print);// output
array[0] = 1
array[1] = 2
array[2] = 3
array[3] = 4
array[4] = 5

We can’t use break or continue inside forEach. If you want to break or continue the loop in the middle, you can use:

  • A for loop
  • every
  • some

The forEach loop doesn’t execute for the empty values

Example 1:

var arr = new Array(3);arr; // [empty × 3]arr.forEach( val  => console.log(val) ); // it prints nothing

Example 2:

var arr = [1,,,,];arr.forEach( val  => console.log(val) ); //output : 1
// it prints 1 then forEach loop will be terminated

Example 3:

var arr = [1,,null, undefined, NaN]arr.forEach( val  => console.log(val) );output:
1
null
undefined
NaN

If the array is modified during iteration, other elements might be skipped

var array = [1,2,3,4,5];array.forEach((value, index, sourceArray) => {

sourceArray.push(10);
console.log(value);
})output :
1,2,3,4,5
array : [1,2,3,4,5,10,10,10,10,10]

In the above example, we added an element on each iteration. But the for-each loop will only be executed for elements and is available in the array during the start of the forEach operation.

Deleting array elements during forEach

If an unvisited element of the array is deleted during the forEach loop, then the elements are skipped \.

var array = [1,2,3,4,5];array.forEach((value, index, sourceArray) => {

sourceArray.pop();
console.log(value);
});output:
1, 2, 3
array:[1,2]

In the above example, we deleted the last element on each iteration. The deleted elements aren’t printed. Her,e only the unvisited elements are skipped. That’s why 3 is printed in the output but deleted in the source array.


Don’t Delete or Add Elements

We shouldn’t use forEach for the modification of elements inside a forEach callback function. It violates the forEach pattern.

Remember forEach is used to execute a function against all elements of the array.


Using the ‘this’ Arg

We can also specify our custom this value when executing a forEach loop.

Example 1 (without passing this):

var array = [1];function log(val, index) {
console.log(this); // window object
}
array.forEach(log);In the above code this --> window

Example 2:

var customThis = {val : 10};var array = [1];function log(val, index) {
console.log(this.val); // 10
}
array.forEach(log, customThis);

Better Programming

Advice for programmers.

Javascript Jeep🚙💨

Written by

Articles related to javascript

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade