-1

When I run the below JS, the console correctly logs a as string: "foo", but then the return value is undefined. typeof() also says it's a string. There is no change from line 5 to 6 (the console.log and the return), so how can this spontaneously become undefined?

let a = "foo";
let c = 0;
function test() {
  if (c === 5) {
    console.log(a);
    return a;
  } else {
    c++;
    test();
  }
}
Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34
Peter Oram
  • 6,213
  • 2
  • 27
  • 40
  • 2
    Or [this one](https://stackoverflow.com/questions/31508709/javascript-recursion-function-returning-undefined) or [this one](https://stackoverflow.com/questions/10762312/javascript-recursive-function-returning-undefined) or [this one](https://stackoverflow.com/questions/36069423/javascript-recursive-function-returns-undefined-for-existing-value). Please do some [basic research](https://www.google.com/search?q=javascript+recursive+function+returns+undefined+site:stackoverflow.com) before asking. – Ivar Jan 07 '20 at 22:08

1 Answers1

2

In your recursive call, use return test():

let a = "foo";
let c = 0;
function test() {
  if (c === 5) {
    console.log(a);
    return a;
  } else {
    c++;
    return test();
  }
}

Explanation: Consider the first call of test() in your original code. If c is 5, it will return a value, but otherwise, it won't return anything. Sure it will execute a second call of test(), but it will not return the value of that call to your main program. This is why the return statement is needed. And the same logic applies to all calls of test() where c is not equal to 5.

Anis R.
  • 6,656
  • 2
  • 15
  • 37