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
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 variablenode
. The second section (node
) verifies the presence ofnode
and as long as it is present (i.e. notnull
orundefined
) the loop persists. The third aspect (node = node.rest
) allows traversing to the subsequent node in the linked structure by accessing therest
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
In this linked list, each node is linked to the following node through its
rest
property. In the last node of the list, thenext
property is set tonull
.So after the loop processes the last element of the list, the assignment
node = node.next
will be equivalent tonode = null
.The looping condition
node
in this context is equivalent tonode != null
, because an object is truthy whilenull
is falsey. So the loop is equivalent to