FAQ: Code Challenges: Intermediate JavaScript - declineEverything() and acceptEverything()

Thank you for your quick answer.

1 Like

my question is also same how the veg get veggies as it is use in decline every function and didnt pass argument there

Hey,

I am having trouble understanding why this wouldn’t work:

const acceptEverything = arr => {
arr.forEach(function(veggie) {
console.log(Ok, I guess I will eat some ${veggie})
})
};

console.log(acceptEverything(veggies));

The console shows:

Ok, I guess I will eat some broccoli
Ok, I guess I will eat some spinach
Ok, I guess I will eat some cauliflower
Ok, I guess I will eat some broccoflower
undefined

First of all, why is there an undefined? Second, why exercise shows error?

In this lesson, we’re asked to write a function declineEverything() that takes in an array of strings and, using .forEach() , loops through each element in the array and calls politelyDecline() with each of them:

https://www.codecademy.com/paths/web-development/tracks/web-dev-js-arrays-loops-objects/modules/web-dev-intermediate-javascript-practice/lessons/intermediate-javascript-coding-challenge/exercises/decline-accept-everything

In order to accomplish this task, we have to write the following code snippet:

const veggies = ['broccoli', 'spinach', 'cauliflower', 'broccoflower'];

const politelyDecline = (veg) => {
      console.log('No ' + veg + ' please. I will have pizza with extra cheese.');
}

// Write your code here:
const declineEverything = arr => {
  arr.forEach(politelyDecline)
};

declineEverything(veggies)

and it prints the following:

No broccoli please. I will have pizza with extra cheese.
No spinach please. I will have pizza with extra cheese.
No cauliflower please. I will have pizza with extra cheese.
No broccoflower please. I will have pizza with extra cheese.

Could anyone explain why don’t we use parentheses () for politelyDecline while passing it in into our arr.forEach() method?

If I put the parentheses () there, it returns undefined and prints the following:

No undefined please. I will have pizza with extra cheese.

Why so?

politelyDecline has one parameter. Shouldn’t we put parenthesis () while using politelyDecline as a callback function?

.forEach() is an iterator method that runs the callback function once for each item in the context array.

context.forEach(callback)

We do not invoke the callback, the iterator does, hence we only pass the function name itself (pass by reference). During iteration the callback is called with the current value as the argument.

1 Like