Home > Software design >  Explain this JavaScript Recursion
Explain this JavaScript Recursion

Time:09-17

Explain this JavaScript Recursion what exactly happens when 0<0 expression does eval for foo(3)?
function-foo returns console.log("test")
Is it that console.log() passed in return statement is unusual?
Is it that the array has two 0's for indices 3 and 4 because foo evals 0 twice because once i-1 reaches 1-1 recursive call should be foo(0) yes?
But continues but console.log is being called twice where foo() recursion call is hoisted between the two what difference does order make here?
I'm not making sense of why exactly these are results

let ar = [];

function foo(i) {
  if (i < 0)
    return console.log("test");

  ar.push(i);
  console.log(i, Boolean(i<0));
  foo(i - 1);
  ar.push(i);
  console.log(i, Boolean(i<0));
}

foo(3)
console.log('ar=', JSON.stringify( ar )) 
.as-console-wrapper { max-height: 100% !important; top: 0 }

CodePudding user response:

your recursive code for foo(3) do:

function foo(i) {
  if (i < 0) return   // stop recursive call
  ar.push(i)          // first push
  foo(i - 1)          // recursive call
  ar.push(i)          // second push
}
ar.push(3)                // ar = [3]         ==== firsts push
    ar.push(2)            // ar = [3,2]
        ar.push(1)        // ar = [3,2,1]
            ar.push(0)    // ar = [3,2,1,0]
                return    // i == -1 , (i<0) is true => no pushS, no foo(i - 1)
            ar.push(0)    // ar = [3,2,1,0,0]  === seconds push
        ar.push(1)        // ar = [3,2,1,0,0,1]
    ar.push(2)            // ar = [3,2,1,0,0,1,2]
ar.push(3)                // ar = [3,2,1,0,0,1,2,3]
  • Related