Home > database >  JavaScript callback function return undefined
JavaScript callback function return undefined

Time:09-13

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

CodePudding user response:

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);

CodePudding user response:

allFruits is a local variable in the listFruits function, you can't access it outside the function.

Instead, countFruits should take its own allFruits parameter. Then it can call the callback function, passing allFruits.length to get it logged.

const fruits = ["Banana", "Mango", "Apple"];
fruits.forEach(listFruits);

function listFruits(allFruits) {
  console.log(allFruits);
}

function countFruits(callback, allFruits) {
  callback(allFruits.length);
}

countFruits(listFruits, fruits);

  • Related