I am trying to write two functions. One contains elements of array with forEach method and another is a callback function that access elements of array from the first function and log their length. The second function is not working and throws Uncaught ReferenceError. I wonder why I get this error.
const fruits = ["Banana", "Mango", "Apple"];
fruits.forEach(listFruits);
function listFruits(allFruits) {
console.log(allFruits);
}
function countFruits(callback) {
callback(allFruits);
console.log(allFruits.length);
}
countFruits(listFruits);
how can i fix this error? and access the length of elements in my callback function , any help will be appreciated
>Solution :
You’re trying to call a function using an array as prop
const fruits = ["Banana", "Mango", "Apple"];
fruits.forEach(listFruits);
function listFruits(allFruits) {
console.log(allFruits);
}
function countFruits(callback) {
// the following line is the problem, "allFruits" are not defined.
// if you change the prop to the array "fruits" the error is solved
callback(fruits);
console.log(fruits.length);
}
countFruits(listFruits);