const arr = ['box', 'piper', 'world'];
arr.forEach(ele => console.log(ele));
// expected output: "box"
// expected output: "piper"
// expected output: "world"
array.forEach(callback [, thisArg])
forEach() calls a given callback function once for each element in an array in ascending order. The second optional argument is the value of this
set in the callback. Index properties that have been deleted or are uninitialized are never invoked by forEach().
const arr = ['box', 'piper', 'world'];
function iterateArr(name) {
console.log(name);
}
arr.forEach(iterateArr);
// expected output: "box"
// expected output: "piper"
// expected output: "world"
In the above example, iterateArr
is the callback function.
arr.forEach(iterateArr)
executes iterateArr
function for every item in the array arr
.
The invocation of iterateArr(name)
function are as follows:
const arr = ['box', 'piper', 'world'];
function iterateArr(name, index) {
console.log(`${name} has index ${index}`);
}
arr.forEach(iterateArr);
// expected output: "box has index 0"
// expected output: "piper has index 1"
// expected output: "world has index 2"
The invocation of iterateArr(name, index)
function are as follows:
array.forEach(callback(item [, index [, array]]))
const arr = ['box', 'piper', 'world'];
/*
The 3rd parameter in iterateArr function
is the array on which forEach() method
was called on.
*/
function iterateArr(name, index, arr) {
console.log(item);
if (index === arr.length - 1) {
console.log('No further elements in an arr');
}
}
arr.forEach(iterateArr);
// expected output: "box"
// expected output: "piper"
// expected output: "world"
// expected output: "No further elements in an arr"
const sparsedArray = ["box", , "piper"];
sparseArray.length;
// expected output: 3
sparsedArray.forEach((item) => {
console.log(item);
});
// expected output: box
// expected output: piper
A sparse array is one, in which the elements do not have contiguous indexes starting at 0.
Only by throwing an exception, we can stop or break a forEach() loop. For early termination of an array iteration, forEach() is not used for. It can easily be done by other array methods like:
forEach() does not wait for promises and expects a synchronous function.
let randomNumbers = [1, 2];
let randomNumbersSum = 0;
async function sumIt(i, j){
return i + j
}
randomNumbers.forEach(async (randomNumber) => {
randomNumbersSum = await sumIt(sum, randomNumber)
})
console.log(randomNumbersSum)
// Naively expected output: 3
// Actual output: 0
array.forEach(callback) method is an efficient way to iterate over all the array items, using callback, items, indexes and even pass a complete array to the callback.
To read extensively about JavaScript Array, MDN DOCS is the only bible which has all the updated information.