each array javascript code example
Example 1: javascript foreach
const avengers = ['thor', 'captain america', 'hulk'];
avengers.forEach((item, index)=>{
console.log(index, item)
})
Example 2: js for each item do
let array = ['Item 1', 'Item 2', 'Item 3'];
array.forEach(item => {
console.log(item);
});
Example 3: javascript .foreach
let colors = ['red', 'blue', 'green'];
colors.forEach(function(color, idx, sourceArr) {
console.log(color, idx, sourceArr)
});
Example 4: javascript foreach
let numbers = ['one', 'two', 'three', 'four'];
numbers.forEach((num) => {
console.log(num);
});
Example 5: forEach
const arraySparse = [1,3,,7]
let numCallbackRuns = 0
arraySparse.forEach((element) => {
console.log(element)
numCallbackRuns++
})
console.log("numCallbackRuns: ", numCallbackRuns)
Example 6: javascript foreach
const colors = ['blue', 'green', 'white'];
function iterate(item) {
console.log(item);
}
colors.forEach(iterate);