This code is showing error and giving me undefined can anyone pls give me logic for this:
const data = ['1','2','3','4','6'];
const consoleItem = (item, index ,arr) =>{
console.log(item);
console.log(index);
console.log(arr);
}
data.forEach(consoleItem())
Your syntax was incorrect. The way you have it setup, it only calls consoleItem
once and it calls it with no parameters, and the return value is used as a parameter to foreach
.
The way I am using it below, consoleItem
is acting as a callback to the forEach
method and I am passing it the three parameters implicitly given by each iteration of the forEach
method.
Try it like this.
const data = ['1','2','3','4','6'];
const consoleItem = (item, index ,arr) =>{
console.log(item);
console.log(index);
console.log(arr);
}
data.forEach(consoleItem)
//data.forEach((x,y,z) => {consoleItem(x,y,z)}) Same as above