Hemant
Hemant

Reputation: 49

JavaScript recursion, understanding in detail

I am not able to understand how this recursion is going to work. Specifically, I'm not able to get a clear idea about how the last console ('end'---) is getting executed. Please provide guidance. Please help me on the execution part. I am not understanding how it is forming the output

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

foo(3);

Upvotes: 1

Views: 87

Answers (3)

Pineda
Pineda

Reputation: 7593

Explanation of how this function executes:

Let's trace out what happens when you invoke this method and pass 3 as an argument:

foo(3);
 // (3<0) false, so skip the return
 // Log out: 'begin: 3'
  //foo (2);
  // (2<0) skip return;
  // Log out: 'begin: 2'
    //foo(1);
      // (1<0) skip return;
      // Log out: 'begin: 1'
      //foo(0);
        // (0<0) false, skip return;
        // Log out: 'begin: 0'
        //foo(-1);
        //(-1 < 0) true!!! 
        //return undefined
      // Log out: 'end: 0'
      //return undefined
    //Log out: 'end: 1'
    //return undefined
  //Log out: 'end: 2'
  //return undefined
//Log out: 'end: 3'
<---return undefined

Actual output:

begin: 3
begin: 2
begin: 1
begin: 0
end: 0
end: 1
end: 2
end: 3
undefined

Upvotes: 4

mychemicalro
mychemicalro

Reputation: 232

First iteration: foo(3) so i=3, then foo(2) is called, i=2, then i=1 and i=0. Now foo(-1) is called. The if condition is now true, so it returns in foo(0) call, where console.log is executed with i=0. Then i=1, i=2, i=3.

So you will have:

begin 3
begin 2
begin 1
begin 0
end 0
end 1
end 2
end 3

Upvotes: 2

Adam  M.
Adam M.

Reputation: 1193

When you call foo(3) what we see is this:

begin: 3
begin: 2
begin: 1
begin: 0
end: 0
end: 1
end: 2
end: 3

what happens in the code is this:

begin: 3
//foo is called, foo(2)
//start of foo(2)
begin: 2
//foo is called, foo(1)
//start of foo(1)
begin: 1
//foo is called, foo(0)
//start of foo(0)
begin: 0
//foo is called, foo(-1)
//start of foo(-1)
//if statement condition is true, returns, ending the recursion chain
//thread returns back to the foo(0) method, logs i
end: 0
//thread returns back to the foo(1) method, logs i
end: 1
//thread returns back to the foo(2) method, logs i
end: 2
//thread returns back to the foo(3) method, logs i
end: 3

Upvotes: 1

Related Questions