title: How does this recursive array permutation function work under the hood?
body: <p>This function generates the permutations of an array.  I've taken pen to paper and put breakpoints in dev tools and painstakingly stepped through each function call, but I'm still not understanding how this is working.  </p>
  
  <p>Specifically, the for loop.  Once the do It function has spliced out all of the numbers in the array it pushes a sliced copy of the temp array into the answer array.  It then splices item into the argument array, pops that same item from the temp array and returns the answer for the first iteration of the for loop.  So after looping through the array once, the answer = [1,2,3] the temp = [1,2] and the arr =[3].</p>
  
  <p>This is where I get lost.  It seems to jump back to the splice and splice 2 back into the arr.  In devTools I put a watch on i, item, temp and arr.  It says that i somehow becomes 1 even though there is only one item in the arr after we've spliced 3 back into it.  If the length is 1 and the for loop specifies it should stop running at arr.length, how does it somehow jump back down to splice 2 back into the array?</p>
  
  <p>I'm sorry if I'm wording this incoherently.  I've spent many hours today going over this.  </p>
  
  <p>Tdlr.  Run this function.  Put a breakpoint at the for loop in the do It function.  Once the array is empty and we return the answer, how does it splice two items back into the original arr. </p>
  
  <pre><code>function permute(arr) {
      var temp = [];
      var answer = [];
  
      function logResult() {
        answer.push(
          // make a copy of temp using .slice()
          // so we can continue to work with temp
          temp.slice()
        );
      }
  
      function doIt() {
        var i;
        var len;
        var item;
  
        for (i = 0, len = arr.length; i &lt; len; i++) {
          // remove the item at index i
          item = arr.splice(i, 1)[0];
          // add that item to the array we're building up
          temp.push(item);
          if (arr.length) {
            // if there's still anything left in the array,
            // recurse over what's left
            doIt();
          } else {
            // otherwise, log the result and move on
            logResult();
          }
          // restore the item we removed at index i
          // and remove it from our temp array
          arr.splice(i, 0, item);
          temp.pop();  
        }
        return answer;
      }
    return doIt();
  };
  
  console.log(permute([1,2,3]));
  </code></pre>
  
  <p>thank you!</p>