Understanding the functionality of for
loops:
Before delving into the intricacies of for
loops, it's essential to grasp their underlying mechanism.
The for
statement establishes a loop that comprises three optional expressions enclosed in parentheses, separated by semicolons, followed by a statement (typically a block statement) to be executed within the loop. MDN
The structure of the for
loop is as follows:
for ([initialization]; [condition]; [final-expression])
statement
The expressions initialization
, condition
, and final-expression
can be any valid expressions. Any or all of these expressions can be omitted (for(;;)
is valid in JavaScript and results in an infinite loop).
The execution of a for
loop commences by performing the initialization
expression if it is specified. Subsequently, it iterates through the following steps: checking if the condition
is true, executing the statement
(s) and final-expression
in sequence if the condition
is true, and halting the loop if the condition
is false.
For instance, consider the diagram below (image source):
https://i.sstatic.net/dr2hY.png
This diagram corresponds to the for
loop presented below:
for(i = 2; i <= 6; i = i + 2)
print i + 1
It is notable that the initialization
part i = 2
is executed only once, while the remaining parts (the condition
, the statement
(s), and the final-expression
) can be executed multiple times (in order) based on the condition
.
Elucidation of the provided code snippet:
for (let node = list; node; node = node.rest) { // big question: how it works or possible?
arrays.push(node.value);
}
The initialization
segment of this loop declares the variable node
and sets its value to the root element list
. This segment is executed only once, at the beginning of the loop.
The condition
part verifies whether node
(the variable) is truthy or not. In JavaScript, an object is truthy while undefined
is falsy. The objective of the loop is to traverse through the object from node to node (as demonstrated in the final-expression
section below). When there is a child node, the subsequent value of node
will be that node (truthy value), leading to a true condition. Conversely, if the child node does not exist, node
will be undefined
(falsy value), resulting in a false condition.
The final-expression
simply assigns the value of node
to the child node of the current node, denoted as node.rest
. When this child node exists, node
is an object; otherwise, it becomes undefined
.