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
});
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)
})
const arr = ["some", "random", "words"]
arr.forEach((word) => { // takes callback and returns undefined
console.log(word)
})
/* will print:
some
random
words */
const arraySparse = [1,3,,7]
let numCallbackRuns = 0
arraySparse.forEach((element) => {
console.log(element)
numCallbackRuns++
})
console.log("numCallbackRuns: ", numCallbackRuns)
// 1
// 3
// 7
// numCallbackRuns: 3
// comment: as you can see the missing value between 3 and 7 didn't invoke callback function.
const names=["shirshak", "John","Amelia"]
//forEach is only for array and slower then for loop and for of loop
//forEach we get function which cannot be break and continue as it is not inside
//switch or loop.
names.forEach((name,index)=> {
console.log(name,index)//
})
let data = ["A", "B", "C", "D"];
function process(element)
{
console.log(element);
}
// With named Function
data.forEach(process);
// With Lambda/anonymous Function
data.forEach((element) => console.log(element));
const colors = ['green', 'yellow', 'blue'];
colors.forEach((item, index) => console.log(index, item));
// returns the index and the every item in the array
// 0 "green"
// 1 "yellow"
// 2 "blue"