Does somebody know why am I still logging undefined?

Does somebody know why am I still logging undefined on line 5 of the output? :slight_smile:

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: // 1 const declineEverything = array => console.log(array.forEach(politelyDecline)); declineEverything(veggies); console.log() // 2 const acceptEverything = array => array.forEach(element => console.log(`Ok, I guess I will eat some ${element}.`)) acceptEverything(veggies);

If a function doesn’t have an explicit return statement, the default return value is undefined. That means, when you have a function like this:

function someFunc(){
  console.log("Hello");
}

and you call it inside a console.log(), like this:

console.log(someFunc());
//the output will be:
//Hello
//undefined

That’s because the function is called, so any console.logs execute, but the return value (which is the default undefined also gets logged, which causes the unwanted undefined at the end of the output.


Notice in your code, the politelyDecline function doesn’t return anything? That means that, when called, any console.logs will execute, but the value returned will be undefined. That means, when you call politelyDecline within a console.log() inside the declineEverything function:

const declineEverything = array => console.log(array.forEach(politelyDecline));
                                   ^^^^^^^^^^^               ^^^^^^^^^^^^^^^

the default return value of politelyDecline (which is undefined), also gets logged.

I hope this helps!

2 Likes

As a general rule, logging is left to the caller, as in log the return value. Have functions return the value to be logged.

const politelyDecline = (veg) => {
  return `No ${veg}, please. I will have pizza with extra cheese.`;
}
const declineEverything = array => array.forEach(item => {
  console.log(politelyDecline(item));
})
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.

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.
1 Like

Amazing help, thank you so much!

1 Like

Thank you so much for your help, I understood it thanks to it! :grinning:

1 Like