title: Understanding execution behind recursion - how does recursion figure out when to stop?
body: <p>I know there are many threads for recursion here. And technically I do understand the principle behind recursion, I'm just more of curious as to where the <strong>actual recursion counter is stored or how does the compiler keep track of it</strong></p>
  
  <p>This is probably better understood by code. I have created a simple recursion function in javascript.</p>
  
  <pre><code>function factorial(number){
      if (number &gt; 1) {
      return number * factorial(number - 1);
    } else {
      return number;
    }
  }
  </code></pre>
  
  <p>Now, everybody understands how this works. We call a recursive function on the factorial which repeats recursively until a function end. </p>
  
  <p>My question would be, how come the factorial function stops executing the recursion at the correct time? If we tried to debug the function in our mind, my understanding is, it would look something like this:</p>
  
  <p>Let's say we called <code>factorial(3);</code> </p>
  
  <blockquote>
    <ol>
    <li>Function Invoked -> Load Arguments</li>
    <li>Calculcate the IF condition -> 3 > 1 -> apply recursive function</li>
    <li>3 * recursive(2) * recursive(1) => 3 * 2 * 1 = 6</li>
    </ol>
  </blockquote>
  
  <p>Now my question is, how is that possible? How come a) if we reduced the recursive counter to 1, we didn't enter the <code>else {</code> statement given it should be evaluated as false, and b) how come the recursive counter knew, to loop the recursive function only number-Nth amount of times?</p>
  
  <p>For better illustration, I added the following line of code
  <code>document.write("entered with number " + number + "&lt;/br&gt;");</code> so we'll print it out every time we enter the if condition.</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function factorial(number){
   if (number &gt; 1) {
     document.write("entered with number " + number + "&lt;/br&gt;");
     return number * factorial(number - 1);
    } else {
     return number;
    }
  }
  
  document.write(factorial(3) + "&lt;br/&gt;");</code></pre>
  </div>
  </div>
  </p>
  
  <p><strong>As you can see, the if condition if condition evaluated as true and printed out the message for 3 and 2. How come the counter didn't loop lower and how come we never returned to the initial <code>else { return number; }</code> if we called the recursive operation on <code>factorial(2-1)</code>?</strong></p>
  
  <p>It is pretty difficult question to word, so if you have any idea on how to formulate it better, feel free to edit my question!</p>