Skip to content
Advertisement

How does empty return statement in conditional statement functions?

Learning JS from MDN Docs came across code in “functions section”. Not able to understand what does return; in the below code accomplish

function foo(i) {
  if (i < 0)
    return; // what does this do? 
  console.log('begin: ' + i);
  foo(i - 1);
  console.log('end: ' + i);
}
foo(3);

Output

'begin: 3'
'begin: 2'
'begin: 1'
'begin: 0'
'end: 0'
'end: 1' // why are these printing
'end: 2' // this one
'end: 3' // this one

I understood first 5 lines of output, but not able to understand why end: 0,1,2,3 are coming?

Please help !

Advertisement

Answer

return terminates the current function, and returns control flow to the caller.

When foo(3); is called, the function is initialized with an i parameter of 3. It fails the if statement, prints begin: 3, and then calls foo(3 - 1);. At this point, the current function (the one with an i parameter of 3) is paused until the foo(3 - 1); call completes.

foo(2); prints begin: 2, and then pauses while calling foo(1).

foo(1) prints begin: 1, and then pauses while calling foo(0).

foo(0) prints begin: 0, and returns: it terminates, and yields control flow back to its caller, the function call of foo(1).

foo(1) resumes, and continues executing, printing end: 1. That’s the end of the function block, so the foo(1) function call ends, yielding control flow back to the foo(2) function call.

foo(2) resumes, printing end: 2, then terminates, yielding control flow back to foo(3). Then foo(3) prints end: 3, and terminates.


return only terminates the current function. The only way to terminate all calling functions (until a catch is encountered) would be to throw an error:

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