The JavaScript forEach() method iterates through the array provided and executes the function passed to it for every element of the array.
Contents
Javascript Developers mostly use forEach() to iterate through an array till the last element instead of using for loop. The forEach() loop will not break in middle, if you have a requirement to break the loop, then forEach() is not a best option for you.
forEach() Method Example
const arr = ['a', 'b', 'c'];
arr.forEach(x => console.log(x));
// expected output: "a"
// expected output: "b"
// expected output: "c"
Syntax
forEach(callbackFn)
forEach((element) => { /* ... */ })
forEach((element, index) => { /* ... */ })
forEach((element, index, array) => { /* ... */ })
Explanation
forEach() calls the provided function once for each element in the ascending order of index.
- callbackFn – call back function.
- element – array element
- index – array current index
- array – array object which is processing.
forEach() doesn’t mutate the elements of the array until explicitly defined in the function passed. It always returns undefined.
Follow us on Facebook, YouTube, Instagram, and Twitter for more exciting content and the latest updates.