Grammar Checker-Cannot read property 'join' of undefined

let count = 0; storyWords = storyWords.forEach((word) => { count++; }); console.log(count); console.log(storyWords.join(' '))

Why do I get the error

console.log(storyWords.join(’ '))

TypeError: Cannot read property ‘join’ of undefined

but when the forEach statement is my last line of code it runs?

Consider what happens here:

storyWords = storyWords.forEach((word) => {



What does the Array.forEach() method return?
See: Array.prototype.forEach() - JavaScript | MDN

1 Like

ah it returns undefined. So when I invoke the method it affects the array downstream?

The issue is the assignment, storyWords = .... This is assigning storyWords to the return value of .forEach() which is undefined, so it is no longer assigned to the array. You can just use the forEach() method on the array without assigning the return value.

For Example:

const myArray = ["Hello", "world.", "How", "are", "you?"]; let count = 0; myArray.forEach(word => count++); const myString = myArray.join(' '); console.log(myArray); console.log(myString); console.log(count);

Thank you for the timely reply you’re awesome!

1 Like