2

I have confusion on function recursion

function foo(i) {
  console.log("checking: " + i);
  if (i < 0)
    return;
  console.log('begin: ' + i);
  foo(i - 1);
  console.log('end: ' + i);
}
foo(1);

why is the output:

checking: 1
begin: 1
checking: 0
begin: 0
checking: -1
end: 0
end: 1

it should not print the end: 0, end: 1, because we are returning in if condition. What is happening?

1 Answer 1

4

return only terminates the most immediately running function.

foo(1)
  foo(0)
    foo(-1)

The

if (i < 0)
  return;

gets fulfilled on the third call, terminating the third function

foo(1)
  foo(0)
    foo(-1) <-- this function stops running

but leaving the other functions to continue as normal:

foo(1)
  foo(0) (execution resumes here, just after the foo(1) line)

It's possible to get out of all ancestor functions (up until a .catch, if any) by throwing an error, but such a strategy just for the sake of control flow isn't a great idea.

function foo(i) {
  console.log("checking: " + i);
  if (i < 0)
    throw new Error();
  console.log('begin: ' + i);
  foo(i - 1);
  console.log('end: ' + i);
}
foo(1);

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

4 Comments

Hi @CertainPerformance, if we use return keywork anywhere inside function it should comeout the function right, then why interpreter comes to console.log('end: ' +i); line. Correct me if I am wrong. Thanks
It only stops the most immediate call, not all calls of the function.
@RabindraKumarMahato the current running function is terminated. As the answer states, there are three different function calls. The third one finishes, the other two are still running.
@RabindraKumarMahato Because return finishes after giving the result ONLY in the current function. It really seems all function is finished after returning. Recursion is difficult I think so too!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.