ES5 class constructor for linked list

sorry, i tried to find a reference in the course but couldn’t, i’m hoping someone can give me a quick reason:

why can’t i just use:

function LinkedList() {
this.head = null;
this.size = 0;

(and then this.head (& this.length/size) as references in the code)
instead of that given below?
it doesn’t work without the functions and initializations seperated.
Your code so far

function LinkedList() {
let length = 0;
let head = null;
this.head = () => head;
this.size = () => length;

function Node(element) {
  this.element = element; = null;

this.add = element => {
  const node = new Node(element);
  if (head) {
    let current = head;
    while ( !== null) {
      current =;
    } = node;
  else {
    head = node;

let list = new LinkedList()

  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.114 Safari/537.36

Challenge: Create a Linked List Class

Link to the challenge:

I think the goal here is to hide the actual head so it can’t be manipulated directly. So you have a “private” variable head which points to the head node but is not accessible from outside the class and then the public function head which allows the user to get the head, but otherwise they cannot change the head. This is very common when using classes, hiding information and then providing public methods to control access to that information.

As for the size, again, you don’t want people to be able to directly access the length because you need to make sure it stays correct and is only changed when a node is added or removed. So you make length a private variable and then provide a size method to get its value.

1 Like

would be nice to get some explanation of that in the challenge. it just feels foreign to me. but thanks.

in fact…that doesnt sound like a requirement of the challenge. i may have to assume my alternative is valid. but i’ll take private variables on board.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.