0

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.

5
  • What's the first thing that's unclear? Commented Oct 30, 2016 at 15:41
  • The list you're using isn't your standard list. It's a LinkedList. To iterate through everything in a linkedlist, you need to keep reading the rest of each "node". Commented Oct 30, 2016 at 15:43
  • 3
    for (var node = list; node; node = node.rest) this initialises node with list. Then it checks if node exists. If yes, then it executes the loop. Next iteration sets node to node.rest Commented Oct 30, 2016 at 15:43
  • Thanks, I guess that's the answer I was looking for! Commented Oct 30, 2016 at 16:02
  • The description given could hardly be clearer. If you still don't understand it, try walking through it line by line in the debugger. Commented Oct 30, 2016 at 16:33

1 Answer 1

1

Your standard for loop would be something like this:

for(var i = 0; i < something; i++)

This initializes the loop with an i of zero. The second argument is a Boolean and if it is true, the loop runs. Finally in den end you increment i by one.

Your loop is the same:

for (var node = list; node; node = node.rest)

It initializes the loop by setting the iterator variable (in this case node) to list. Then it does the Boolean check (is there a node) and finally it sets the current node to rest.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.