1

Hey I am not able to understand this JavaScript code properly:

 foo(i) {
     if (i < 0)
         return;

     console.log('begin: ' + i);

     foo(i - 1);
     console.log('after: ' + i);
 }

 foo(3);

Output

begin: 3
begin: 2
begin: 1
begin: 0
after: 0
after: 1 
after: 2
after: 3

So I know what's happened inside the code for first four output but not able to understand what's happened inside the code for last four output pls someone explain this code in details for last four output it will be really helpful for me.

Andreas
  • 21,535
  • 7
  • 47
  • 56
Aakash Giri
  • 53
  • 1
  • 8

1 Answers1

2

So this example shows the recursive function call as it executes :

 function foo(i)
  {
    if(i<0)
    return;
    console.log('begin: ' +i); // Line 1
    foo(i-1);  // Line 2
    console.log('after: ' +i);  // Line 3
  }
  foo(3);

What happens is first you call Line 1, then call the function again at Line 2, and then Line 3

So the execution stack looks like this

console.log('begin: ' +3); // Line 1
foo(2);  // Line 2
console.log('after: ' +3);  // Line 3

Now next Line 2 would again be converted to :

console.log('begin: ' +3); // Line 1
console.log('begin: ' +2); // Line 1
foo(1); // Line 2
console.log('after: ' +2);  // Line 3

console.log('after: ' +3);  // Line 3

and so forth

console.log('begin: ' +3); // Line 1
console.log('begin: ' +2); // Line 1
console.log('begin: ' +1); // Line 1
foo(0); // Line 2
console.log('after: ' +1);  // Line 3
console.log('after: ' +2);  // Line 3

console.log('after: ' +3);  // Line 3

And final iteration :

console.log('begin: ' +3); // Line 1
console.log('begin: ' +2); // Line 1
console.log('begin: ' +1); // Line 1
console.log('begin: ' +0); // Line 1
foo(-1) // Line 2 for negative value, we are exiting the recursion.
console.log('after: ' +0);  // Line 3
console.log('after: ' +1);  // Line 3
console.log('after: ' +2);  // Line 3

console.log('after: ' +3);  // Line 3
binariedMe
  • 4,309
  • 1
  • 18
  • 34
  • How the value of `i` is increasing in `console.log('after)` – brk Mar 03 '18 at 09:02
  • Its not increasing. If you see... The value passed to foo is decreasing and that is coming before the second console so the decreased value is getting printed first. – binariedMe Mar 03 '18 at 09:11
  • so where these values of `i` is getting stored before consoling – brk Mar 03 '18 at 09:13