'Mutation in javascript?
In the below code size2()
method working fine.But in size1()
it is mutating the object and making it null.why such behavior is not happening in size2()
?
class Node {
constructor(data, next = null) {
this.data = data;
this.next = next;
}
}
class LinkedList {
constructor() {
this.head = null;
}
insert(data) {
this.head = new Node(data, this.head);
}
size1() {
var counter = 0;
while (this.head) {
counter++;
this.head = this.head.next;
}
return counter;
}
size2() {
var counter = 0;
var node = this.head;
while (node) {
counter++;
node = node.next;
}
return counter;
}
}
var list = new LinkedList();
list.insert(35);
console.log(list);
console.log(list.size2());
To me both the method looks same. Is there any subtle difference in those methods?
Solution 1:[1]
In size2()
, you are not mutating this.head
because you first copy the reference in a local variable. Since in the while
loop you are mutating the local node = node.next
starting here node
and this.head
are not linked any more. It's the eternal Value/Reference pitfall.
Here is a related article.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | जलजनक |