use of foreach in 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: js foreach
var stringArray = ["first", "second"];
myArray.forEach((string, index) => {
var msg = "The string: " + string + " is in index of " + index;
console.log(msg);
});
Example 4: foreach loop javascript
const numList = [1, 2, 3];
numList.forEach((number) => {
console.log(number);
});
Example 5: js get index from foreach
var myArray = [123, 15, 187, 32];
myArray.forEach(function (value, i) {
console.log('%d: %s', i, value);
});
Example 6: foreach javascript
Used to execute the same code on every element in an array
Does not change the array
Returns undefined