I'm following the Eloquent JavaScript course, and I've came to an exercise in which you have to produce an array from a list.
This is the list:
var list = {value: 10, rest: {value: 20, rest: null}}
And this is the "suggested" code/procedure:
function listToArray(list) {
var array = [];
for (var node = list; node; node = node.rest)
array.push(node.value);
return array;
}
I'm struggling to understand the for loop line, can someone please explain it to me, step by step?
I mean, it is explained in the course:
To run over a list (in listToArray and nth), a for loop specification like this can be used:
for (var node = list; node; node = node.rest) {}
Can you see how that works? Every iteration of the loop, node points to the current sublist, and the body can read its value property to get the current element. At the end of an iteration, node moves to the next sublist. When that is null, we have reached the end of the list and the loop is finished.
But I wanted to understand how every single step "works" (maybe with examples), if it's possible.
listyou're using isn't your standard list. It's a LinkedList. To iterate through everything in a linkedlist, you need to keep reading therestof each "node".for (var node = list; node; node = node.rest)this initialisesnodewithlist. Then it checks ifnodeexists. If yes, then it executes the loop. Next iteration setsnodetonode.rest