Home > OS >  I want to return undefined but instead got "{"
I want to return undefined but instead got "{"

Time:03-03

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"))

CodePudding user response:

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

CodePudding user response:

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)
    }else{
     return undefined
    }
  }
}

fearNotLetter("abcdefghijklmnopqrstuvwxyz")
  • Related