title: tail call optimization javascript
body: <p>NOTE: This is just for studying and bettering myself. I know of the available sort method for arrays. I'm just trying to get the basics of TCO down.</p>
  
  <p>Currently trying to work on a sort algorithm using recursion. However when I try to process large datasets (+4000 objects), I am still getting a stack overflow error. I'm trying to implement TCO. I'm fairly new to the concept but I think I have the gist of it. However, I'm still receiving a stack overflow error. </p>
  
  <pre><code>const sort = (arr, counter) =&gt; {
    if (!counter) {
      counter = arr.length - 1;
    }
    for (let n = 1; n &lt;= counter; n++) {
      if(arr[n - 1] &lt; arr[n]) {
        let placeHolder = arr[n];
        arr[n] = arr[n - 1];
        arr[n - 1] = placeHolder;
      }
    }
    counter -= 1;
    return counter === 0 ? arr : sort(arr, counter);
  };
  
  function sortRecursive(arr) {
    return sort(arr);
  }
  </code></pre>
  
  <p>UPDATE:</p>
  
  <p>I managed to get it working, but I don't quite understand why. I managed to handle 100,000 recursions with no problems. I had to move the boolean that checks if counter is defined. However, I do not quite understand why that made it work.</p>
  
  <pre><code>const sort = (arr, counter) =&gt; {
    if (!counter) {
      counter = arr.length - 1;
    }
    for (let n = 1; n &lt;= counter; n++) {
      if(arr[n - 1] &lt; arr[n]) {
        let placeHolder = arr[n];
        arr[n] = arr[n - 1];
        arr[n - 1] = placeHolder;
      }
    }
    counter -= 1;
    if (counter === 0) {
      return arr;
    } else {
      return sort(arr, counter);
    }
  };
  
  function sortRecursive(arr) {
    return sort(arr, arr.length - 1);
  }
  </code></pre>
  
  <p>OUTPUT:</p>
  
  <pre><code>let firstArr = [];
  let secondArr = [];
  
  for (let x = 0; x &lt; 100000; x++) {
    firstArr.push(Math.ceil(Math.random() * 100000));
    secondArr.push(Math.ceil(Math.random() * 100000));
  }
  
  sortRecursive(firstArr);
  //Array[100000]
  </code></pre>