Stuck on Eloquent Javascript

Hello, apparently I got stuck on Chapter 4.3 A list

Here’s the full working code for reference:

function arrayToList(array) {
  let list = null;
  for (let i = array.length - 1; i >= 0; i--) {
    list = {value: array[i], rest: list};
  }
  return list;
}

function listToArray(list) {
  let array = [];
  for (let node = list; node; node = node.rest) {
    array.push(node.value);
  }
  return array;
}

function prepend(value, list) {
  return {value, rest: list};
}

function nth(list, n) {
  if (!list) return undefined;
  else if (n == 0) return list.value;
  else return nth(list.rest, n - 1);
}

console.log(arrayToList([10, 20]));
// → {value: 10, rest: {value: 20, rest: null}}
console.log(listToArray(arrayToList([10, 20, 30])));
// → [10, 20, 30]
console.log(prepend(10, prepend(20, null)));
// → {value: 10, rest: {value: 20, rest: null}}
console.log(nth(arrayToList([10, 20, 30]), 1));
// → 20

I reviewed the arrayToList function, already. I understood it fine.

I’m currently reviewing the listToArray function and this is what I’m confused about:

(let node = list; node; node = node.rest)

What exactly is going on on this for loop? I don’t understand the condition.

Thanks for the help! I’m coming back on the same thread if I still don’t understand something on the solution, if you don’t mind :slight_smile:

remember that a loop has three parts:

for (<start>; <condition>; <iteration>)  {
   <body>
}

the start is executed before the loop starts, then the condition is checked, if it’s true or truthy then the body of the loop is executed, otherwise the loop stops, after the body the iteration happens, and then again the condition is checked to evaluate if the loop continues or not

remembering this, can you figure out what the loop is doing?

Thank you for your reply!

Oh, yes, I know this, definitely. Perhaps I’ll ask for a clarification, instead?

Because this is how I’m currently reading the loop:

So, the starting point and the condition is:

The iteration part set the node = node.rest

Does that mean the list and list.rest is now stored in the for loop and we are able to push the values of the list to a new array?

I’m very sorry if this was unclear. I’m trying my best to understand it

I will point out that this is a bizarre use of a for loop and I would reject this code in a review. This would be better expressed with a while loop:

let node = list;
while (node) {
  array.push(node.value);
  node = node.rest;
}

Nothing is ‘stored’ in the for loop. The loop is traversing the data structure.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.