0

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

9
  • What are you trying to do? Commented Sep 12, 2022 at 21:08
  • 2
    Well, you haven't actually defined allFruits. It's just the name of an incoming function argument. What do you expect its value to be? Commented Sep 12, 2022 at 21:09
  • 2
    callback(allFruits); -> allFruits is not defined in this scope. This is a variable defined only in the scope of listFruits function. Commented Sep 12, 2022 at 21:09
  • @ kelly i want to print length of all fruits in callback function Commented Sep 12, 2022 at 21:13
  • callback(fruits.length) Commented Sep 12, 2022 at 21:15

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.