js foreach array code example

Example 1: javascript foreach

const avengers = ['thor', 'captain america', 'hulk'];
avengers.forEach((item, index)=>{
	console.log(index, item)
})

Example 2: javascript foreach

var colors = ['red', 'blue', 'green'];

colors.forEach(function(color) {
  console.log(color);
});

Example 3: for each js

const fruits = ['mango', 'papaya', 'pineapple', 'apple'];

// Iterate over fruits below

// Normal way
fruits.forEach(function(fruit){
  console.log('I want to eat a ' + fruit)
});

Example 4: foreach javascript

let words = ['one', 'two', 'three', 'four'];
words.forEach((word) => {
  console.log(word);
});
// one
// two
// three
// four

Example 5: js foreach

var stringArray = ["first", "second"];

myArray.forEach((string, index) => {
  	var msg = "The string: " + string + " is in index of " + index; 
	console.log(msg);
	
	// Output:
	// The string: first is in index of 0
	// The string: second is in index of 1
});

Example 6: javascript foreach example

var colors = ["red", "blue", "green"];
colors.forEach(function(color) {
    console.log(color);
});