javascript foreach item code example
Example 1: javascript foreach
const avengers = ['thor', 'captain america', 'hulk'];
avengers.forEach((item, index)=>{
console.log(index, item)
})
Example 2: foreach in javascript
var a = ["a", "b", "c"];
a.forEach(function(entry) {
console.log(entry);
});
var fruits = ["apple", "orange", "cherry"];
fruits.forEach(myFunction);
function myFunction(item, index) {
document.getElementById("demo").innerHTML += index + ":" + item + "<br>";
}
Example 3: how to use the foreach method in javascript
groceries.forEach(groceryItem => console.log(groceryItem));
Example 4: javascript foreach object
function logArrayElements(element, index, array) {
console.log('a[' + index + '] = ' + element)
}
[2, 5, , 9].forEach(logArrayElements)