Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error in linkedList forEach method? #21

Open
pemigra opened this issue Jan 12, 2018 · 2 comments
Open

Error in linkedList forEach method? #21

pemigra opened this issue Jan 12, 2018 · 2 comments

Comments

@pemigra
Copy link

pemigra commented Jan 12, 2018

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.

@RebootJeff
Copy link
Collaborator

RebootJeff commented Jan 12, 2018

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

@pemigra
Copy link
Author

pemigra commented Jan 13, 2018

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants