Mini Linter Step 4 > Is it right code?

I used forEach method inside for loop and this is working!
But I am not sure if this is right way or not …
I would appreciate any advice !
Thank you

project link - https://www.codecademy.com/paths/web-development/tracks/web-dev-js-arrays-loops-objects/modules/learn-javascript-iterators/projects/mini-linter


let story = 'Last weekend, I took literally the most beautiful bike ride of my life. The route is called "The 9W to Nyack" and it actually stretches all the way from Riverside Park in Manhattan to South Nyack, New Jersey. It\'s really an adventure from beginning to end! It is a 48 mile loop and it basically took me an entire day. ....';
const storyWords = story.split(' ');
const overusedWords = ['really', 'very', 'basically'];
/// count and log over used words
let count = [0, 0, 0];
const overWords = () => {
  for (let i = 0; i < overusedWords.length; i++) {
    betterWords.forEach((word) => {
      if (word === overusedWords[i]) {
        count[i]++;
      }
    });
    console.log(`The words ${overusedWords[i].toUpperCase()} was used ${count[i]} times in the story`);
  }
};

overWords();

You don’t need a for loop because .forEach already iterates through the array. Look at this example:

const overusedCount = storyWords.forEach(word => {
  if (word === 'really') countReally++;
  if (word === 'very') countVery++; 
  if (word === 'basically') countBasically++;

As you can see, storyWords is calling the method .forEach here. .forEach will go through every element inside storyWords and assign it to word, which is the argument variable we are using in this example (before the =>).

Lastly, thinking about .forEach like a loop. Now that you have each item, you can do anything you want with it. In this example, it checks what kid of word it is and if it matches, it adds it to a separate counter. Hope it helps!

1 Like

I have a quick question, what if the overusedWords array had so many values?
I used a for loop because I didn’t want to write all the overusedWords values (‘really’ ‘very’ ‘basically’) inside the .forEach. In this way, Can I use a for loop with forEach just like I asked before? or should I use forEach twice? or is there a better way to do it ? :joy:

Thank you for your kind solution anyway :grinning:
It really helped me to understand how .forEach works!

1 Like

well, if you think of .forEach like a for loop, then this would be a similar situation to 2 nested for loops right? So you could have .forEach first, and then inside of it have a for loop to check every word in overusedWords against the words from storyWords

1 Like