Search code examples
javascriptoperator-keyword

Missing letters freecodecamp


Actually I found an answer a few minutes ago. But I found something strange.

This is my answer for 'Missing letters' in freeCodeCamp challenges.

function fearNotLetter(str) {

var string; 

for (i=0;i<str.length;i++) {
  if(str.charCodeAt(i)+1 < str.charCodeAt(i+1)){
    string = String.fromCharCode(str.charCodeAt(i)+1);
 }
}

return string;

}  

When I change < operator in if statement into != (not same), it doesn't work! For me, it seems that != works exactly same as < operator does. (Because 'not same' can mean something is bigger than the other.)

What is the difference between < and != in the code above?


Solution

  • Your code has a small defect that works when you use < but not !=.

    If you see str.charCodeAt(i+1); this code is checking one spot past the end of the string on the last iteration and will return a NaN result.

    If I provide the string "abce" it will check if f is < NaN. I believe NaN can't be compared to f's value so it doesn't go into the if statement. So it will keep the missing letter d that was found in the previous iterations which is stored in your string variable.

    However, if you provide the !=, then with the same scenario it knows f != NaN and goes into the if statement. This then overwrite the actual missing letter and fails your FCC test case because it is replacing the missing d with f in your string variable.

    To fix your code, simply change the for loop to end one iteration before the length of the string.

    for (i = 0; i != str.length-1; i++) {
    }