Javascript forEach method

Manikandan L
4 min readSep 21, 2023

--

The Javascript forEach is one of the way to iterate the Array of Elements.The Elements may be string, number, boolean, undefined, objects, arrays, all mixed together and so on … can able to iterate.

Note: *Important forEach will not call the callback function for empty values in the array.

Eg: let arr = [1,2,”array”,’’markAntony’,true, false, undefined, {name:”Antoty”, age:29}, [1,2,3,4]] this is the example of all javascript data types present in the array.

Syntax:

let arr = [1,2,3,4,5,6]

// using arrow function
arr.forEach((n)=>{console.log(n)}) ==> 1,2,3,4,5,6

// using normal function

arr.forEach(function(n){console.log(n)}) ==> 1,2,3,4,5,6
const words = ['one', /*empty */,  'two', /*empty */, 'three', /*empty */,  
'four', /*empty */];

words.forEach((word) => {
console.log(word); // one two three four
});

console.log(words); // ['one','two', 'three', 'four']

---------------------------

let num = [1, 2, 3, 4];
num[10] = 10;
num.forEach((word) => {
console.log(word); // 1 2 3 4 10
});

console.log(num); // [ 1, 2, 3, 4, <6 empty items>, 10 ]

The above one is the example for iteration is not happening or callback function not called for the empty values

The forEach methods executes a provided function once for each array of elements in ascending-index order.

In the above part (n)=>{} || function(n){} referred as the callback function of the forEach methods and this callback function accepts three arguments/parameters

  1. Element (mandatory) => The value of the current array element
  2. index(optional) => The current element’s index number
  3. array(optional) => The array object to which the current element belongs

Another Syntax:

let num = [1, 2, 3, 4];

num.forEach(callBackFun);

function callBackFun(n) {
console.log(n); // 1 2 3 4
}

--------------------------------

let num = [1, 2, 3, 4];

num.forEach(callBackFun);

function callBackFun(n, i, arr) {
console.log(n, i, arr);
}
//n i arr
1 0 [ 1, 2, 3, 4 ]
2 1 [ 1, 2, 3, 4 ]
3 2 [ 1, 2, 3, 4 ]
4 3 [ 1, 2, 3, 4 ]

In the above code arguments like n,i,arr attached to the callbackFun automatically by javascript

Another Important Point, forEach functions expects a synchronous function and it does not work for asynchronous function and does not wait for Promise also.

Example 1:

function testProm(val) {
return new Promise((res) => {
res(val);
});
}

let nums = [1, 2, 3, 4, 5];

nums.forEach(async (num) => {
console.log('start', num);
console.log('fromPromise', await testProm(num));
console.log('end', num);
});

//output

start 1
start 2
start 3
start 4
start 5
fromPromise 1
end 1
fromPromise 2
end 2
fromPromise 3
end 3
fromPromise 4
end 4
fromPromise 5
end 5

In the above program, for each iteration a callback function or function will executed simultaneously without wait, because await keyword is inside in the callback function

So the callback function will execute the first line, that console.log(), then move to the second line and in the we have keyword called await, while reaching that word, that function will wait until the result get from the promise , in the mean time the other function from the second iteration will execute and follow the same, once the result get from the promise will execute the below lines, and rest other callback functions also will follow the same procedure.

Example 2:

const nums = [5, 4, 5];
let sum = 0;

const sumFunction = async (a, b) => a + b;

nums.forEach(async (n) => {
sum = await sumFunction(sum, n);
});

console.log(sum);

// expected output: 14
// Actual output: 0

In the above program for each iteration a callback function will also execute, it will wait for the result from promise, but the forEach will not wait it executes all loops or iteration, after the iteration or loop of forEach the last line console.log(sum) will executed, still the sum value is 0 only, because the callback fun is waiting for result.

break, continue, and return these are not working inside in the forEach

In JavaScript, the continue, break,statement is typically used within loops like for and while, but it cannot be used directly within a forEach loop. The forEach loop is specifically designed to iterate over elements in an array and execute a provided callback function for each element. It does not support break or continue statements like traditional loops do.

  1. Not able to ‘break’ the forEach Loop
let arr = [1, 2, 3, 4];
arr.forEach(function(item) {
console.log(item);

if (item === 2)
break;
});
// Output: Uncaught SyntaxError: Illegal break statement

The above code throwing an error, because break statement only works in normal for loop

let arr = [1, 2, 3, 4];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);

if (arr[i] === 2)
break;
}
// Output: 1 2

2. Not able to ‘continue’ the forEach Loop

let arr = [1, 2, 3, 4];
arr.forEach(function (ele) {
if (ele === 2)
continue;

console.log(ele);
});
// Output: Uncaught SyntaxError: Illegal continue statement: no surrounding iteration statement

The above code throwing an error, because continue statement only works in normal for loop

3. ‘return’ doesn’t stop looping

let arr = [1, 2, 3, 4];
arr.forEach(function (ele) {
console.log(ele);

if (ele === 2)
return;

});
// Output: 1 2 3 4

we all know the return keyword is must be the last word of every function, because javascript won’t execute code below the return keyword and after the return keyword js stop executing the function.

In the above code we attached the return keyword inside in the callback function, thats only we get the ouputs, it won’t throw any error like continue and break.

--

--