0

The code below is a PUSH method of singly linked list in javascript which adds a element to the tail value in the list.

How come the 1st output shows the linked list before passing the argument inside the PUSH() method?

The first console.log logs an empty object of the list but inside the object the values of the passed arguments which is passed later is given.

How come this is possible??

class Node {
  constructor(val) {
    this.val = val;
    this.next = null;
  }
}

class SinglyLinkedList {
  constructor() {
    this.head = null;
    this.tail = null;
    this.length = 0;
  }

  // PUSH
  push(val) {
    const newNode = new Node(val);

    if (!this.head) {
      this.head = newNode;
      this.tail = newNode;
    } else {
      this.tail.next = newNode;
      this.tail = newNode;
    }

    this.length += 1;
    return this;
  }
}

// 1st output
console.log(list);

list.push("Hi");
list.push("You");
list.push(25);
list.push(2);

// 2nd output
console.log(list);

OUTPUT

1ST console.log(list)

    SinglyLinkedList {head: null, tail: null, length: 0}
                   head: Node {val: 'Hi', next: Node}
                   length: 4
                   tail: Node {val: 2, next: null}
                   [[Prototype]]: Object
           

2ND console.log(list)

    SinglyLinkedList {head: Node, tail: Node, length: 4}
                   head: Node {val: 'Hi', next: Node}
                   length: 4
                   tail: Node {val: 2, next: null}
                   [[Prototype]]: Object
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • the console evaluates the object when you inspect it in the console - by then, the `push` have been done (unless your extremely quick, like nanosecond quick) – Bravo Mar 09 '22 at 04:46
  • in firefox, the first console log looks like `Object { head: null, tail: null, length: 0 }` though, when you expand it, those properties now have values ... because the expansion inspects the object at the time you expand it - if you `console.log(JSON.parse(JSON.stringify(list)))` that won't happen – Bravo Mar 09 '22 at 04:50

0 Answers0