title: Trying to understand recursion within for loops in javascript
body: <p>I've been staring at the answer to this question forever even writing down variables and whatnot through each iteration.  I simply just don't get the process here.  When I throw in console logs I see that permute is called input.length - 1 times before it ever gets to this line input.splice(i, 0, ch);  It's hard to phrase the question when I am lost completely, but I guess some curiosities are: each time permute is called, it is a new instance of that function with it's own closure right? therefore variables changes that are within the function won't affect variables in other calls?  does the function return permArr for each time it's called? and I suppose that doesn't necessarily affect the return of the first call? (my instinct tells me that the first time return happens, the function stops running).</p>
  
  <p>Thanks for the insight.</p>
  
  <p><a href="https://stackoverflow.com/questions/9960908/permutations-in-javascript">Permutations in JavaScript?</a></p>
  
  <pre><code>var permArr = [],
  usedChars = [];
  
  function permute(input) {
    var i, ch;
    for (i = 0; i &lt; input.length; i++) {
      ch = input.splice(i, 1)[0];
      usedChars.push(ch);
      if (input.length == 0) {
          permArr.push(usedChars.slice());
      }
      permute(input);
      input.splice(i, 0, ch);
      usedChars.pop();
    }
    return permArr
  };
  </code></pre>