Q:

foreach javascript

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

colors.forEach(function(color) {
  console.log(color);
});
44
const avengers = ['thor', 'captain america', 'hulk'];
avengers.forEach((item, index)=>{
	console.log(index, item)
})
28
let words = ['one', 'two', 'three', 'four'];
words.forEach((word) => {
  console.log(word);
});
// one
// two
// three
// four
21
let numbers = ['one', 'two', 'three', 'four'];

numbers.forEach((num) => {
  console.log(num);
});  // one   //two //three // four
8
const numList = [1, 2, 3];

numList.forEach((number) => {
  console.log(number);
});
2
var items = ["item1", "item2", "item3"]
var copie = [];

items.forEach(function(item){
  copie.push(item);
});
11
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
});
0
const arr = [10,20,30,40]

arr.forEach(function(item, index){
    console.log(item, index);
})
3
let colors = ['red', 'blue', 'green'];
// idx and sourceArr optional; sourceArr == colors
colors.forEach(function(color, idx, sourceArr) {
	console.log(color, idx, sourceArr)
});
// Output:
// red 0 ['red', 'blue', 'green']
// blue 1 ['red', 'blue', 'green']
// green 2 ['red', 'blue', 'green']
7
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']
8

New to Communities?

Join the community