1

lets take this example

function main (x) {
    return x
}

function second() {
    console.log("hello ")
}


js compiler knows all function declarations so I can call second inside main main(second()) what I dont get about recursive functions is that how the same function can be called inside the function declaration


function factorial(n) {
 if (n ===1) {
 return 1;
 } else {
 return n * factorial(n-1);
 }
}

my thought process is: okay this is the function declaration this is what the function does, but how can
can i call the same function even if the declaration is not finished

Liam
  • 27,717
  • 28
  • 128
  • 190
herbert mühlex
  • 261
  • 4
  • 14
  • 2
    Javascript is not interpreted in the classical sense, it doesn't execute your code line-by-line. – georg Apr 21 '21 at 08:50
  • 1
    compiler !== interpretation These are different things that work differently so be a little careful with your language on this – Liam Apr 21 '21 at 08:53
  • 1
    Call stack? There is a nice visualization https://felixgerschau.com/javascript-event-loop-call-stack/ – Ivar Apr 21 '21 at 08:59
  • 1
    also [because function hoisting](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting) – Liam Apr 21 '21 at 08:59

1 Answers1

1

Because the function doesn't run when it is being defined. It only runs later, when it is called.

A function's code is the recipe for performing a computation. If at some point it calls another function it means the execution continues according to that recipe, and then when that is finished, the execution comes back to after the calling point, and resumes from there.

It doesn't matter whether you call the same function though. It just means that same recipe will be followed. But, crucially, each invocation is an independent copy of the recipe, each running independently in its own environment like call stack frame etc., which is what makes recursion possible.

See also these answers by me that talk about it some more, or that one.

Will Ness
  • 70,110
  • 9
  • 98
  • 181