Missing letters

Please could someone explain how this solution works? I am stuck on if(charCode !== str.charCodeAt(0) + i)

This is from https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/missing-letters

function fearNotLetter(str) {
 //using loop
 for(let i = 0; i < str.length; i++){
   const charCode = str.charCodeAt(i);
   //codes are:97-a 98-b 99-c 101-e
  
  if(charCode !== str.charCodeAt(0) + i){
   //why is charCode not starting from 97, and i being 3??
    return String.fromCharCode(charCode - 1)
  }
 }
return undefined;

}

console.log(fearNotLetter("abce"));

Thanks in advance!

This checks if charCode is not equal to the character code str’s first character plus the current value of i. If the first letter in the string was a (charCode of 97), then the first iteration of the for loop, i would be 0, so the char code of the first letter would be the same as the In the case of str.charCodeAt(0) + i. During the second iteration, charCode would be b (charCode of 98) and since i would be 1, str.charCodeAt(0) + 1 would be the same charCode (98). This would keep going until the 4th iteration, where the charCode for e would be 101 and i would be 3. str.charCodeAt(0) + 3 would be 97 + 3 (or 100), so they would not match, and hence the return statement would return the letter before e.

Ahhh so it keeps looping until the condition - if(charCode !== str.charCodeAt(0) + i) is met. Thank you for the explanation.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.