skip to Main Content

If you scroll to the bottom of this page https://eloquentjavascript.net/04_data.html you will see ‘Display Hints’ under the heading ‘A List’. Click that and then you will see hints where there is a line of code that I don’t understand:

Code:

for (let node = list; node; node = node.rest) {}

Why is the 2nd part of the for loop say nothing but ‘node’? Is this the same as saying node == true?
The last part of the for loop says ‘node.rest’. What does that do? Does .rest mean anything specific?

The book gives an explanation but it’s not enough for me to grasp it so I’m hoping someone can break it down in a simple manner

2

Answers


  1. This for construct serves the purpose of iterating through the list of nodes, which are interlinked objects. The first part (let node = list) establishes the starting position of the list by storing it in the variable node. The second section (node) verifies the presence of node and as long as it is present (i.e. not null or undefined) the loop persists. The third aspect (node = node.rest) allows traversing to the subsequent node in the linked structure by accessing the rest reference that leads to the following node in the sequence.

    The .rest is not a reserved word; it simply serves as an identifier for the child element, which is used to link the current chain to the next one, and is often referred to as .next in other such programs. The above loop continues in a serial manner visiting all the chain links until the last link is opened. It is like a path in which every move leads to another!

    Please let me know if you have any further queries. I would be more than happy to answer

    Login or Signup to reply.
  2. In this linked list, each node is linked to the following node through its rest property. In the last node of the list, the next property is set to null.

    So after the loop processes the last element of the list, the assignment node = node.next will be equivalent to node = null.

    The looping condition node in this context is equivalent to node != null, because an object is truthy while null is falsey. So the loop is equivalent to

    for (let node = list; node != null; node = node.rest)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search