title: Remove node from Singly Linked List
body: <p>I'm implementing a remove function for LL in Javascript. </p>
  
  <p>Here's my function:</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>//Define Node obj
  function Node(data){
    this.data = data;
    this.next = null;
  }
  
  //Define SinglyList obj
  function SinglyList(){
    this._length = 0;
    this.head = null;
  }
  
  SinglyList.prototype.add = function(val){
    var node = new Node(val),
        currentNode = this.head;
  
        //If empty, build as first node
        if(!currentNode){
          this.head = node;
          this._length++;
          return;
        }
  
        //iterate over until end of list
        while(currentNode.next){
          currentNode = currentNode.next;
        }
  
        //add/append new node
        currentNode.next = node;
        this._length++;
  
        return node;
  };
  
  SinglyList.prototype.remove = function(index){
    var currentNode = this.head, count=0, previous;
    //if list is empty, exit out
    if(this._length===0) return;
  
    //Check if first node
    if(index===0){
        this.head = currentNode.next;
        this._length--;
    }else{
  
        while(count&lt;index){
          previous = currentNode;
          currentNode = currentNode.next;
          count++;
        }//end while
  
        previous.next = currentNode.next;
  
        return previous;
    }// end if
  
  };
  
  var singlyList = new SinglyList();
  
  singlyList.add(1);
  singlyList.add(2);
  singlyList.add(3);
  singlyList.add(4);
  singlyList.add(5);
  singlyList.add(6);
  singlyList.add(7);
  singlyList.add(8);
  singlyList.add(9);
  singlyList.add(10);
  
  console.log(JSON.stringify(singlyList));
  console.log('Remove:\n'+JSON.stringify(singlyList.remove(5)));</code></pre>
  </div>
  </div>
  </p>
  
  <p>Problem: If i had 10 nodes in my list and called this function to remove 5th node, this function only returns 4th-10th nodes where 5th is removed. However, i'd expect it to return 1-10th where 5th is removed. What am i doing wrong and how can i retrieve a list where only the 5th node is removed?</p>