0

I have some code where I am able to exit out of the code however whatever is returned is undefined which is weird given if i console.log what I want to return it gives the correct value. Here is my code:

function encryptPass(text, result) {
        var a = text.length -1;
        var c = text.charCodeAt(a);
        if      (65 <= c && c <=  90) result += String.fromCharCode((c - 65 + 4) % 26 + 65);  // Uppercase
        else if (97 <= c && c <= 122) result += String.fromCharCode((c - 97 + 4) % 26 + 97);  // Lowercase
        else                          result += text.char;  // Copy
        
        if (a == 0) {
            console.log(result);
            return result;
        } else {
          encryptPass(text.substr(0, a), result);
        }       
       return; 
    }
console.log('lemons '+ encryptPass('hello',''));
matisetorm
  • 857
  • 8
  • 21
  • Don't quote the variable in `return 'encrypted'`. – Barmar Nov 13 '17 at 20:50
  • 1
    **1.** `return 'encrypted';` should be `return encrypted;` (to return the value of the variable `encrypted` not the string `"encrypted"``). – ibrahim mahrir Nov 13 '17 at 20:50
  • 2
    **2.** `encryptPass(text.substr(0, a), result);` should be `return encryptPass(text.substr(0, a), result);` (so the whole recursion return a value eventually). – ibrahim mahrir Nov 13 '17 at 20:51
  • 1
    and you're missing a `return` in the else block. should be `return encryptPass(text.substr(0, a), result);` – Joel Kornbluh Nov 13 '17 at 20:51
  • Thanks that solved it, barmar it was to test that it wasn't what I wanted to return was the issue. –  Nov 13 '17 at 20:53
  • **3.** the last `return` statement is useless (if you fix **2.**) as it is never reached due to the `else` block. – ibrahim mahrir Nov 13 '17 at 20:53

1 Answers1

0

You have 2 problems:

    if (a == 0) {
        encrypted = result;
        return 'encrypted'; // you return the word encrypted instead of the variable results
    } else {
      encryptPass(text.substr(0, a), result);
    }      
    return; // you return undefined

Solution:

function encryptPass(text, result) {
  var a = text.length - 1;
  var c = text.charCodeAt(a);
  if (65 <= c && c <= 90) result += String.fromCharCode((c - 65 + 4) % 26 + 65); // Uppercase
  else if (97 <= c && c <= 122) result += String.fromCharCode((c - 97 + 4) % 26 + 97); // Lowercase
  else result += text.char; // Copy

  if (a == 0) {
    return result; // return the result
  }

  // you can skip the else check, since this is only option left
  return encryptPass(text.substr(0, a), result); // return the results of encryptPass
}
console.log('lemons ' + encryptPass('hello', ''));
Ori Drori
  • 183,571
  • 29
  • 224
  • 209