xxxxxxxxxx
const avengers = ['thor', 'captain america', 'hulk'];
avengers.forEach(element => {
//Statement
console.log(element);
});
xxxxxxxxxx
var colors = ["red", "blue", "green"];
colors.forEach(function(color) {
console.log(color);
});
xxxxxxxxxx
const numList = [1, 2, 3];
numList.forEach((number) => {
console.log(number);
});
xxxxxxxxxx
Array.forEach() is a method in JavaScript that is used to iterate over the elements of an array. The method takes a callback function as an argument, which is executed once for each element in the array. The callback function takes three arguments: the current element, the index of the current element, and the array being traversed.
Here is an example of how to use Array.forEach():
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(element, index, array) {
console.log(element, index, array);
});
This will output:
1 0 [1, 2, 3, 4, 5]
2 1 [1, 2, 3, 4, 5]
3 2 [1, 2, 3, 4, 5]
4 3 [1, 2, 3, 4, 5]
5 4 [1, 2, 3, 4, 5]
In this example, the callback function takes three parameters, the current element, the index of the current element and the array being traversed. Here the function will be called for each element in the array and the element, index, and array are passed as arguments to the callback function.
xxxxxxxxxx
const fruits = ['apple', 'orange', 'banana', 'mango'];
fruits.forEach((item, index)=>{
console.log(index, item)
});
xxxxxxxxxx
// foreach method of array in javascript
let numberArray = [1,2,3,4,5];
function printArrayValue(value, index){
console.log(`value: ${value} = index: ${index}`);
}
numberArray.forEach(printArrayValue);
// Output:
// value: 1 = index: 0
// value: 2 = index: 1
// value: 3 = index: 2
// value: 4 = index: 3
// value: 5 = index: 4
xxxxxxxxxx
arr.forEach(function (item, index, array) {
// ... do something with item
});
xxxxxxxxxx
const array = ['Element_1', 'Element_2', 'Element_3']
array.forEach((currentElement, currentElementIndex, arrayOfCurrentElement) => {
console.log(currentElement, currentElementIndex, arrayOfCurrentElement)
})
xxxxxxxxxx
const scores = [22, 54, 76, 92, 43, 33];
scores.forEach((score) => {
console.log(score);
});
// You can write the above in one line this way:
// scores.forEach((score) => console.log(score));
// will return
// 22
// 54
// 76
// 92
// 43
// 33