I’ve implemented a linked list in JavaScript, and the code is fully functional. However, I’m encountering a puzzling behavior related to JavaScript’s private fields.
Here’s the issue: Despite declaring the data and next fields as private within the Node class, I’m still able to assign values to the next field from within the LinkedList class.
class Node {
#data;
#next;
constructor(data, next = null) {
this.#data = data;
this.#next = next;
}
getData() {
return this.#data;
}
}
class LinkedList {
#head;
#tail;
#size;
constructor() {
this.#head = null;
this.#tail = null;
this.#size = 0;
}
addLast(data){
const node = new Node(data);
if(!this.#head) {
this.#head = node;
this.#tail = node;
} else {
this.#tail.next = node;
this.#tail = node;
}
this.#size++;
}
remove(data){
if(!this.#head) return false;
if(this.#head.getData() === data) {
this.#head = this.#head.next;
if(!this.#head) {
this.#tail = null;
}
this.#size--;
return true;
}
let current = this.#head;
while(current.next){
if(current.next.getData() === data){
current.next = current.next.next;
if(!current.next) this.#tail = current;
this.#size--;
return true;
}
current = current.next;
}
return false;
}
reverse() {
if (!this.#head ) {
console.log('The list is empty');
return;
}
let prevNode = null;
let currentNode = this.#head;
this.#tail = this.#head;
while (currentNode) {
const nextNode = currentNode.next;
currentNode.next = prevNode;
prevNode = currentNode;
currentNode = nextNode;
}
this.#head = prevNode;
}
printList() {
let current = this.#head;
while(current) {
console.log(current.getData());
current = current.next;
}
}
}
const superList = new LinkedList();
superList.addLast(10);
superList.addLast(20);
superList.addLast(30);
superList.addLast(40);
console.log("BEFORE REVERSE: ")
superList.printList();
superList.reverse();
console.log("AFTER REVERSE: ")
superList.printList();
Specifically, how does this line of code execute without error?
this.#tail.next = node;
I’m puzzled as to how the LinkedList class can access the private #next field of a Node instance. Any insights or explanations would be greatly appreciated!
Iurii Senchkovskii is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1