How is this recursive function resolved and why does it output what it does

I could not understand this example of a recursive function:

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

Conclusion:

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

I understand how normal and nested functions work, and I think that return;it should exit the function when iit becomes smaller than 0, therefore, when i = -1, the first console.log()didn’t show, but why foo(-1 - 1)do we get the exit afterwards end:0?

+4
source share
2 answers

To understand that you have to visualize the stack. Let me complete the execution process:

  • foo(3), i 3. i 0, log begin:3. foo(2)
  • i 2. i 0, log begin:2. foo(1)
  • i 1. i 0, log begin:1. foo(0)
  • i 0. i 0, log begin:0. foo(-1)
  • i -1. i 0, . , , log foo(0):

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

    end:0 , i 0. foo(0) , foo(1)

  • foo(1). end:1 , i 1. foo(1) , foo(2)
  • foo(2). end:2 , i 2. foo(2) , foo(3).
  • foo(3). end:3 , i 3. foo(3) , , .

:

begin:3 //Step 1
begin:2 //Step 2
begin:1 //Step 3
begin:0 //Step 4
end:0   //Step 5
end:1   //Step 6
end:2   //Step 7
end:3   //Step 8

, :

foo (-1 - 1) : 0?

foo(-1 - 1), foo(-1) - . , end:i, i , , , , foo(i - 1). , end:i, .

+6

, do , = 0, foo (i-1) console.log('end:' + i); console.log('begin:' + i); i.

, :

  • Foo (3)
    • = 3 → display: "begin 3";
    • foo (2)
      • = 2 → display: "begin 2";
      • foo (1)
        • = 1 → display: "begin 1";
        • foo (0)
          • = 0 → display: "begin 0";
          • foo (-1) → return
          • foo (0), "end 0"
          • foo (0)
        • foo (1), "end 1"
        • foo (1)...

.

+2

Source: https://habr.com/ru/post/1659358/


All Articles