JavaScript forEach()

I ran into a quirk that maybe has some documentation reason behind it, but the code running here adds an undefined entry after the expected result. Any help in this is appreciated. Code:

const decimals = [0.75, 0.91, 0.48, 0.23, 0.99, 0.83, 1.1]; function logPercentages(decimals) { const percentages = (decimals) => console.log(`${Math.round(decimals*100)}` + "%"); decimals.forEach(percentages); } console.log(logPercentages(decimals));

And here is the result of running the code:

75%
91%
48%
23%
99%
83%
110%
undefined

Ideas?

The function logPercentages does not return anything. Therefore the console logs ‘undefined’.

const fn = () => {}
console.log(fn()); // logs 'undefined'

Just call the function:

logPercentages(decimals);

No need to log the function call.

Thanks for that! I guess I need to pay attention to when something needs a return and when it doesn’t. Of course, this was a sample code of something I worked on back in boot camp last year and found I had an error that got passed for some reason.

Truly helpful in my understanding journey!

1 Like