Search code examples
javascriptfor-loopundefined

I want to return undefined but instead got "{"


In this code I want to return the alphabet that's missing in a string of continuous alphabets, and if all alphabets are present I want to return undefined. However, instead returning defined, it returns "{" and I can't find similar cases anywhere online.

function fearNotLetter(str) {

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

console.log(fearNotLetter("abcdefghijklmnopqrstuvwxyz"))


Solution

  • here in your example inside for loop you are returning

    String.fromCharCode(str.charCodeAt(i)+1)
    

    in this return value when charecter is z , where has ascii value of 'z' is 122 and you are returning 122+1 that is asci value of '{'

    thats why you are getting '{' in your example

    you can test by removing 'z' from passed string in your function