xxxxxxxxxx
// array for the forEach method
let grades = [13, 12, 14, 15]
// for each loop
grades.forEach(function(grade) {
console.log(grade) // loops and logs every grade of the grades array
})
xxxxxxxxxx
const fruits = ['mango', 'papaya', 'pineapple', 'apple'];
// Iterate over fruits below
// Normal way
fruits.forEach(function(fruit){
console.log('I want to eat a ' + fruit)
});
xxxxxxxxxx
let words = ['one', 'two', 'three', 'four'];
words.forEach((word) => {
console.log(word);
});
// one
// two
// three
// four
xxxxxxxxxx
var items = ["item1", "item2", "item3"]
var copie = [];
items.forEach(function(item){
copie.push(item);
});
xxxxxxxxxx
var colors = ["red", "blue", "green"];
colors.forEach(function(color) {
console.log(color);
});
xxxxxxxxxx
var array = ["a","b","c"];
// example 1
for(var value of array){
console.log(value);
value += 1;
}
// example 2
array.forEach((item, index)=>{
console.log(index, item)
})
xxxxxxxxxx
let numbers = ['one', 'two', 'three', 'four'];
numbers.forEach((num) => {
console.log(num);
}); // one //two //three // four
xxxxxxxxxx
var fruits = ["apple", "orange", "cherry"];
fruits.forEach(getArrayValues);
function getArrayValues(item, index) {
console.log( index + ":" + item);
}
/*
result:
0:apple
1:orange
2:cherry
*/
xxxxxxxxxx
const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));
// expected output: "a"
// expected output: "b"
// expected output: "c"
xxxxxxxxxx
const arr = ["some", "random", "words"]
arr.forEach((word) => { // takes callback and returns undefined
console.log(word)
})
/* will print:
some
random
words */