English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The syntax of forEach is;
let arr = [element1, element2, elementN]; arr.forEach(myFunction(element, index, array, this){ function body });
The myFunction function executes element in arr. element is passed as a parameter to the function during each iteration, and the array is passed as a parameter to the function.
In this example, we will apply forEach to each element of the array.
let array1 = ['a1', 'b1', 'c1']; array1.forEach(function(element) { console.log(element); });
Output Result
a1 b1 c1
In this example, we will apply forEach to each element of the array. Then, we define the function separately and pass it as a parameter to forEach.
let array1 = ['a1', 'b1', 'c1} let myFunc = function(element) { console.log(element) } array1.forEach(myFunc)
In this example, we will access the index, array, and element in each iteration.
let array1 = ['a1', 'b1', 'c1} let myFunc = function(element, index, array) { console.log(index + ' : ' + element + ' - ' + array[index]) } array1.forEach(myFunc)
Output Result
0 : a1 - a1 1 : b1 - b1 2 : c1 - c1