Example 1: javascript foreach
const avengers = ['thor', 'captain america', 'hulk'];
avengers.forEach((item, index)=>{
console.log(index, item)
})
Example 2: foreach jas
const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));
Example 3: javascript .foreach
let colors = ['red', 'blue', 'green'];
colors.forEach(function(color, idx, sourceArr) {
console.log(color, idx, sourceArr)
});
Example 4: forEach
const arraySparse = [1,3,,7]
let numCallbackRuns = 0
arraySparse.forEach((element) => {
console.log(element)
numCallbackRuns++
})
console.log("numCallbackRuns: ", numCallbackRuns)
Example 5: for each javascript
const movies = [
{name: "A New Hope", director: "George Lucas", release: "1977-05-25", episodeID: 4},
{name: "Attack of the Clones", director: "George Lucas", release: "2002-05-16", episodeID: 2},
{name: "Return of the Jedi", director: "Richard Marquand", release: "1983-05-25", episodeID: 6},
{name: "Revenge of the Sith", director: "George Lucas", release: "2005-05-19", episodeID: 3},
{name: "The Empire Strikes Back", director: "Irvin Kershner", release: "1980-05-17", episodeID: 5},
{name: "The Phantom Menace", director: "George Lucas", release: "1999-05-19", episodeID: 1}
]
movies.forEach((movies) => {
console.log(movies.name);
});
Example 6: foreach javascript
Used to execute the same code on every element in an array
Does not change the array
Returns undefined