Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript callback function return undefined

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading