Where is the undefined value coming from?

Hi,

For the code task - https://www.freecodecamp.org/challenges/missing-letters

I had this solution now, it must be simple but when i would add else to my surprise-

else{
return undefined;
}

It does not work
But when i remove it , it was working…my confusion is , from where is the undefined coming from as demanded by the task … thanks …


function fearNotLetter(str) {
   var test = [];
  var res,res1;
    for(var i = 0; i< str.length;i++){
        test.push(str.charCodeAt(i));
    }
    
    for(var j = 0; j < test.length-1;j++){
        if(test[j+1] - test[j] > 1){
           res = test[j+1]-1;
            console.log(res);
           res1 = String.fromCharCode(res);
          }
         //      else{
          //               return undefined;
           //        }
      
      
        }
            
 // console.log(res1);
    return res1;

}

fearNotLetter("bcd");

when you do that at the start of the code, you are setting up the variables but not defining them as anything (a string, a number, an array) so if the if statement conditions aren’t met, you will return res1 as undefined

from: undefined - JavaScript | MDN

A variable that has not been assigned a value is of type undefined. A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value.

1 Like

If you didn’t assign a value to a variable, it implicitly is undefined. In this case, if the for-loop finishes running without satisfying the condition in the if-block, the res1 variable remains undefined.

2 Likes

@DarrenfJ, @kevcomedia - thanks , seems i unknowingly did that , but i now understand it …

Regards

1 Like