for each loop in javascript code example
Example 1: javascript loop through array
var data = [1, 2, 3, 4, 5, 6];
for(let i=0; i<=data.length; i++) {
console.log(data[i])
}
for(let i of data) {
console.log(i)
}
for(let i in data) {
console.log(i)
console.log(data[i])
}
data.forEach((i) => {
console.log(i)
})
data.map((i) => {
console.log(i)
})
Example 2: javascript for loop
var colors=["red","blue","green"];
for (let i = 0; i < colors.length; i++) {
console.log(colors[i]);
}
Example 3: javascript foreach
const avengers = ['thor', 'captain america', 'hulk'];
avengers.forEach((item, index)=>{
console.log(index, item)
})
Example 4: javascript foreach
var colors = ['red', 'blue', 'green'];
colors.forEach(function(color) {
console.log(color);
});
Example 5: javascript loop
let array = ['Item 1', 'Item 2', 'Item 3'];
array.forEach(item => {
console.log(item);
});
Example 6: for each js
const fruits = ['mango', 'papaya', 'pineapple', 'apple'];
fruits.forEach(function(fruit){
console.log('I want to eat a ' + fruit)
});