Why does it not return undefined when applicable?

Hi Everyone. I’ve been solving this specific challenge for JavaScript.

“Find the missing letter in the passed letter range and return it.
If all letters are present in the range, return undefined.”

I’ve managed to return the missing letter, but I cannot get the code to return undefined when there is no missing letter. Could you guys help me understand why it doesn’t return undefined in this case, so I can know how to handle this in the future? The code is below:


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

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

(If I put ‘abcde’ in the console.log, it just returns nothing, instead of ‘undefined’).

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

markdown_Forums

1 Like
str.charCodeAt(i+1)

When no letter is missing, what is this value on the very last loop?

1 Like

Ohhh ok, I guess it’s gonna try to pull a letter that doesn’t exist (last item +1). Thanks, I’ll try to alter the code.

and that nothing what is it?
because if the function doesn’t execute a return statement it returns undefined by default
the question is a different one, how to avoid the if statement executing when it shouldn’t?

if I add console.log({i, "str.charCodeAt(i+1)": str.charCodeAt(i+1), "str.charCodeAt(i)": str.charCodeAt(i), "str.charCodeAt(i+1) - str.charCodeAt(i) != 1": str.charCodeAt(i+1) - str.charCodeAt(i) != 1}) as first line inside the loop, with the function call fearNotLetter("abcde"), this is what appear in the console, note the true in last one

{
  i: 0,
  'str.charCodeAt(i+1)': 98,
  'str.charCodeAt(i)': 97,
  'str.charCodeAt(i+1) - str.charCodeAt(i) != 1': false
}
{
  i: 1,
  'str.charCodeAt(i+1)': 99,
  'str.charCodeAt(i)': 98,
  'str.charCodeAt(i+1) - str.charCodeAt(i) != 1': false
}
{
  i: 2,
  'str.charCodeAt(i+1)': 100,
  'str.charCodeAt(i)': 99,
  'str.charCodeAt(i+1) - str.charCodeAt(i) != 1': false
}
{
  i: 3,
  'str.charCodeAt(i+1)': 101,
  'str.charCodeAt(i)': 100,
  'str.charCodeAt(i+1) - str.charCodeAt(i) != 1': false
}
{
  i: 4,
  'str.charCodeAt(i+1)': NaN,
  'str.charCodeAt(i)': 101,
  'str.charCodeAt(i+1) - str.charCodeAt(i) != 1': true
}

and in that case newLetter has value of NaN, and what is returned is String.fromCharCode(NaN); which seems to give value of "\u0000", which doesn’t seem to appear in the console

1 Like