Setting the Node.next to a given element in Linked Lists

Hey there, still new to data structures and had some problems working with linked lists. The FCC challenge is here: https://learn.freecodecamp.org/coding-interview-prep/data-structures/create-a-linked-list-class

When trying to set the inputted node element as the Node.next of an existing element, I ran into trouble. My code is here:

function LinkedList() { 
  var length = 0; 
  var head = null; 

  var Node = function(element){
    this.element = element; 
    this.next = null; 
  }; 

  this.head = function(){
    return head;
  };

  this.size = function(){
    return length;
  };

  this.add = function(element){
    // Only change code below this line
    let newNode = new Node(element);

		if(length == 0){
			head = newNode;
			length = 1;
		}
		else{
			let nextNode = head;
			for(let i=0; i<length; i++){
				nextNode = nextNode.next;
			}

			nextNode = newNode;
			length += 1;
		}
    // Only change code above this line
  };
}

When I submit, I get an error “Cannot read property ‘element’ of null”, which leads me to think that ‘head’ is still pointing to ‘null’ somehow, even though my solution already passed the test for setting head to new Node(). I’m not really sure what to do

You spelled “length” wrong in your loop.

Sorry, that was based on old code, will fix. The error still stands for my updated code.

Hi all, I eventually moved on and came back to this problem later, and realized where I went wrong.
The code for finding the next node used a for loop starting at i = 0 should instead have started at i = 1. Then, instead of setting nextNode = newNode, it should’ve been written as nextNode.next = newNode, like thus:

            let nextNode = head;
			for(let i=1; i<length; i++){
				nextNode = nextNode.next;
			}

			nextNode.next = newNode;
			length += 1;

This would account for the error that I was recieving. Thanks!