Undefined from a while loop?

codepen

I’m getting my first two test cases, of returning the missing letter in a string, but I’m not sure about getting the undefined from a while loop?

function fearNotLetter(str) {
  var index = 0;
  console.log(str.charCodeAt(index));
  while (str.charCodeAt(index+1) === str.charCodeAt(index)+1) {
   index++;
}
   var str=(String.fromCharCode(str.charCodeAt(index)+1))

  
  return str;
}//end of ferNotLetter(str)

//fearNotLetter("abce");  // should return "d".
//fearNotLetter("abcdefghjklmno");  // should return "i".
fearNotLetter("bcd");  //should return undefined.
fearNotLetter("yz");   //should return undefined.

The problem is your loop causes a defined value. You need to put it into a separate value…

function fearNotLetter(str) {
  var index = 0;
  var missingLetter;
  
  while (index < (str.length - 1)) {
    if (str.charCodeAt(index+1) !== str.charCodeAt(index)+1) {
       missingLetter = String.fromCharCode(str.charCodeAt(index)+1);
       index = str.length;
    }
    index++;
  }
    return missingLetter;
}
//end of ferNotLetter(str)

console.log(fearNotLetter("abce"));  // should return "d".
console.log(fearNotLetter("abcdefghjklmno"));  // should return "i".
console.log(fearNotLetter("bcd"));  //should return undefined.
console.log(fearNotLetter("yz"));   //should return undefined
1 Like

Try this.

function fearNotLetter(str) {
  var index = 0;
  //console.log(str.charCodeAt(index));
  while (str.charCodeAt(index+1) === str.charCodeAt(index)+1) {
   index++;
}
  var result = undefined;

  if (index < str.length-1)
    {
   result =(String.fromCharCode(str.charCodeAt(index)+1))
   }
  
  return result;
}//end of ferNotLetter(str)

console.log(fearNotLetter("abce"));  // should return "d".
console.log(fearNotLetter("abcdefghjklmno"));  // should return "i".
console.log(fearNotLetter("bcd"));  //should return undefined.
console.log(fearNotLetter("yz"));   //should return undefined.


/*   

function fearNotLetter(str) {
  var numbers = str.split('').map(function(letter){
    return letter.charCodeAt(0);
  });
  
  for (var i = 0; i<numbers.length; i++){
    
    if (numbers[i+1] - numbers[i] > 1){
      return String.fromCharCode(numbers[i] + 1);
    }
    
  }
}
 
//letters to charCode array [1,2,3,5]
//iterate through array to find missing number
//return charCode > Letter of missing number


*/

Thank you, that does seem to work and is passing all the test… I’m just confused where this undefined is coming from. If it was the first line, I’d think it was a remnant of running through the loop before… but it looks like it’s continuing to do something after it finds the correct answer.

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