HOW TO USE forEach JAVASCRIPT 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: foreach javascript

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

Example 4: javascript foreach example

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

Example 5: foreach javascript

var items = ["item1", "item2", "item3"]
var copie = [];

items.forEach(function(item){
  copie.push(item);
});

Example 6: foreach javascript

let names = ['josh', 'joe', 'ben', 'dylan'];
// index and sourceArr are optional, sourceArr == ['josh', 'joe', 'ben', 'dylan']
names.forEach((name, index, sourceArr) => {
	console.log(color, idx, sourceArr)
});

// josh 0 ['josh', 'joe', 'ben', 'dylan']
// joe 1 ['josh', 'joe', 'ben', 'dylan']
// ben 2 ['josh', 'joe', 'ben', 'dylan']
// dylan 3 ['josh', 'joe', 'ben', 'dylan']

Tags:

Dart Example