Missing Letters Challenge

Tell us what’s happening:

Hey guys! Cant figure out why this isn’t working. Any ideas? The function works, but doesn’t returned undefined.

Your code so far


function fearNotLetter(str) {

  for  (var i = 0; i < str.length; i++){
        
    if (str.charCodeAt(i) !== str.charCodeAt(i + 1) - 1){
     let result = String.fromCharCode(str.charCodeAt(i + 1)-1); 
     return result;
    }
    
  }
  return undefined;
}

fearNotLetter("abce");

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36.

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

That is because your if statement never evaluates to false. You can see why if you put the following console.log statement on the line before the if statement.

console.log(str.charCodeAt(i), str.charCodeAt(i+1)-1)  

When the last test case runs, you will notice the last comparison it makes is 122 to NaN. That evaluates to true which is why it returns NaN for it.

I’m guessing this means I have to reformat my function, because I don’t see a way around it in its current state.
Thanks btw!

No, you could add an extra condition inside your existing if statement which also checks the the next character str[i+1] is not undefined. Another additional condition you could add would be to check if i is less than str.length minus 1. Either of these last two additional conditions is basically checking if you have reached the last character in the string or not.

thanks for clearing that up, I actually tried the second condition you mentioned when i created the function but I set a check for i = str.length ass opposed to i < str.length - 1, forgetting that str.length is not an indexed number.