Q:

javascript for each loop

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

// Iterate over fruits below

// Normal way
fruits.forEach(function(fruit){
  console.log('I want to eat a ' + fruit)
});
15
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
/** 1. Use forEach and related */
var a = ["a", "b", "c"];
a.forEach(function(entry) {
    console.log(entry);
});

/** 2. Use a simple for loop */
var index;
var a = ["a", "b", "c"];
for (index = 0; index < a.length; ++index) {
    console.log(a[index]);
}

/**3. Use for-in correctly*/
// `a` is a sparse array
var key;
var a = [];
a[0] = "a";
a[10] = "b";
a[10000] = "c";
for (key in a) {
    if (a.hasOwnProperty(key)  &&        // These checks are
        /^0$|^[1-9]\d*$/.test(key) &&    // explained
        key <= 4294967294                // below
        ) {
        console.log(a[key]);
    }
}

/** 4. Use for-of (use an iterator implicitly) (ES2015+) */
const a = ["a", "b", "c"];
for (const val of a) {
    console.log(val);
}

/** 5. Use an iterator explicitly (ES2015+) */
const a = ["a", "b", "c"];
const it = a.values();
let entry;
while (!(entry = it.next()).done) {
    console.log(entry.value);
}
5
var colors = ["red", "blue", "green"];
colors.forEach(function(color) {
    console.log(color);
});
13
const array1 = ['a', 'b', 'c'];

array1.forEach(element => console.log(element));
20
let array = ['Item 1', 'Item 2', 'Item 3'];

array.forEach(item => {
	console.log(item); // Logs each 'Item #'
});
6
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
groceries.forEach(groceryItem => console.log(groceryItem));
4
var sum = 0;
var obj = {prop1: 5, prop2: 13, prop3: 8};

for each (var item in obj) {
  sum += item;
}

console.log(sum); // logs "26", which is 5+13+8
2

New to Communities?

Join the community