Why wont it add it multiple times?

S during this project im using iterators to modify a story. Well im on this part which wants me to let the user know how many times they used a specific set of words(each individually) but when im doing it this way it keep only counting it then reseting that value and counting the next one causing ‘really’ to be counted 1 time and out putting 1 2 times when it should be counted as 2 and logged 1 time. The hint says to use if statements but the solution video uses a for loop and ‘of’ which is something ive never been taught or used so i dont want to copy it. Could someone explain how i can manage to this with simple if else statement? (it also causes an undefined to be outputted at the end too)

Current Project

const youSaid = betterWords.forEach(word => {
  let word1 = 0;
  let word2 = 0;
  let word3 = 0;
  if (overusedWords[0] === word) {
    return console.log('You said ' + word + ': ' + word1 + ' time(s).');


every iteration in the forEach method has its own scope. Just move the assignments out of the method:

let word1 = 0;
let word2 = 0;
let word3 = 0;
const youSaid = betterWords.forEach(word => {

forEach does not return anything. And if you log something to the console, that is not necessary anyway. You can just remove the keyword return.

omggggg it worked! I cant believe it was that simple. Okay so is there a way to make it print just once? would a different method be more sufficient? Like right now it logs…

You said really: 1 time(s).
You said really: 2 times(s).

how can i get it to just say

You said really: 2 time(s).

Would i have to log it separately from the block or something?

Yes, you could move the console out of the forEach block and log it only once.
For that purpose, you would have to make your variables with the word counts an object with a key that is the word itself and a value that is the word count.

ahhhh seems a bit out of my grasp at the moment but i appreciate the insight!

1 Like