algoClass
algoClass copied to clipboard
Error in linkedList forEach method?
In the definition of the LinkedList.forEach function:
LinkedList.prototype.forEach = function(callback) { var node = this.head; while (node) { callback(node.value); node = node.next; } };
Doesn't the node = node.next;
line incorrectly refer only to a reference (node.next), rather than an actual node object?
Thanks.
Great question
But why is a reference incorrect?
In short, it's actually ok because a reference is all that's needed.
When the while
loop goes through each iteration, the JavaScript interpreter will...
- Look up "what does
node
refer to?" - Find that it refers to an instance of
Node
. - Look for the
value
property of that node object. - Invokes the
callback
with whatever thevalue
property has. - Look up "what does
node
refer to?" - Find that it refers to an instance of
Node
. - Look for the
next
property of that node object. - Assign
node
to whatever thenext
property has (which is a reference to another node). - Check the
while
condition.
The long answer is: variables always store references to objects rather than "actual" objects. There is no other option. For example...
var x = {}; // even at this point, `x` merely refers to the empty object
var y = x;
var z = y;
x = z;
z.name = 'Peter';
console.log(x.name); // "Peter"
console.log(y.name); // "Peter"
console.log(z.name); // "Peter"
// ...because all 3 variables refer to the same object.
Mutability
Another way to think about it is in terms of "mutability". Objects are mutable. If you keep this in mind, you could actually ignore concerns about "what is or isn't just a reference" and still manage to write perfectly good JavaScript code.
Feel free to ask for clarification. Ya never know when an answer is confusing due to complexity of the topic or just due to a typo. 😝
Super, thanks for the great response. My confusion was that I was stuck on originally thinking that node.next had to simply point to another node's value only, rather than the node instance itself. Makes complete sense once I realized that mistake on my part.