Stefano De Rosso
Stefano De Rosso

Reputation: 1339

List to array in JavaScript

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.

Upvotes: 0

Views: 278

Answers (1)

Falk
Falk

Reputation: 637

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.

Upvotes: 1

Related Questions