.forEach( ) returning undefined

Hello all,

I have being traying to get my head around it to understand why this is returning undefined and not the sum of the words ending with ‘!’ or ‘.’. Can someone help me to understand what I am missing here?

const storyWords = ['Today', 'is', 'Sunday.', 'It', 'is', 'a', 'beautiful', 'day!', 'My', 'son', 'and', 'I', 'will', 'play', 'football!'];

const howManySentences = storyWords.forEach((word) => {
  let counter = 0;
    if (word.endsWith('!') || word.endsWith('.')) {
     return counter ++;
  }  
})

console.log(howManySentences); // return undefined

Hi @hendriler
welcome to the forum!
you are trying to assign multiple array items to the variable howManySentences. That would be done with the method map() rather than forEach().
Yet I don’t think that you want howManySentences to be an array but just a number, right?
Then simply declare counter in the global scope and reassign counter with forEach() like this:

let counter = 0;
storyWords.forEach((word) => {
  
    if (word.endsWith('!') || word.endsWith('.')) {
     counter ++;
  }  
})

console.log(counter); // 3
1 Like

Thank you very much! It does make a lot of sense…

1 Like