-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();
  }
}
1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.