algoClass icon indicating copy to clipboard operation
algoClass copied to clipboard

Error in linkedList forEach method?

Open pemigra opened this issue 7 years ago • 2 comments

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.

pemigra avatar Jan 12 '18 21:01 pemigra

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...

  1. Look up "what does node refer to?"
  2. Find that it refers to an instance of Node.
  3. Look for the value property of that node object.
  4. Invokes the callback with whatever the value property has.
  5. Look up "what does node refer to?"
  6. Find that it refers to an instance of Node.
  7. Look for the next property of that node object.
  8. Assign node to whatever the next property has (which is a reference to another node).
  9. 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. 😝

RebootJeff avatar Jan 12 '18 21:01 RebootJeff

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.

pemigra avatar Jan 13 '18 05:01 pemigra