Missing letters_Not understanding why my code isn't working

Tell us what’s happening: Hello. When I console.log my count variable, it outputs only zeroes. I wondered if someone could tell my why it’s not incrementing. Thanks!

Your code so far


function fearNotLetter(str) {
  let alphabet = "abcdefghijklmnopqrstuvwxyz";
  let begin = alphabet.indexOf(str[0]);
  for (let i = begin; i < begin + str.length; i++) {
    let count = 0;
    if (alphabet[begin] !== str[count]) {
      return alphabet[begin];
      count++;
    } else {
      return undefined;
    }
  }
}

fearNotLetter("abce");

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/missing-letters

return exits out of the function.

If you hit the return line, then yes, you’re going to exit out of the immediate function (which in your case I believe is fearNotLetter)

I would like for it to exit out of the function if this condition is met. My intention is for the count variable to increment if the condition isn’t met.

function fearNotLetter(str) {
  let alphabet = "abcdefghijklmnopqrstuvwxyz";
  let index = alphabet.indexOf(str[0]);
  for (let i = index; i < index + str.length; i++) {
    let count = 0;
    if (alphabet[i] !== str[count]) {
      console.log(str[i]);
      return alphabet[i];
    } else {
      console.log(count++);
      count++;
    }
  }
}

fearNotLetter("stvwx");

Was going off your first code, which had a return in the if and else, so it would have only run once.

No, thanks! I realized I hadn’t updated it. I’m stumped though as to why my variable isn’t incrementing.

My guess is that you are placing let count in a very precarious place. If you know what scope is, I need to ask, what is the scope of let count?

1 Like

I’ve studied scope a little but in this case, I don’t quite understand why when kept in the for-loop, the count variable doesn’t increment.

This code cleared the challenge:

function fearNotLetter(str) {
  let alphabet = "abcdefghijklmnopqrstuvwxyz";
  let index = alphabet.indexOf(str[0]);
  let count = 0;
  for (let i = index; i < index + str.length; i++) {
    if (alphabet[i] === str[count]) {
      count++;
    } else {
      return alphabet[i];
    }
  }
}

it’s important where you place let count. Because you placed let count within the for loop, the scope of that variable is limited to the for loop. It also means that each time you iterate through the for loop, you count becomes 0 again.

It works now because you are no longer resetting count.

Ah yes. It makes sense now.