What is the function of a variable in a for loop conditional place?

Viewed 26

I have a function that converts a list to an array.

function listToArray(list) {
    let arr = [];

    for (let node = list; node; node = node.rest) {
        arr.push(node.value);
    }

    return arr;
}

What's confusing to me is the node variable in the for loop. This bolded node: (let node = list; node; node = node.rest). How that bolded "node" works? What it is used for?

1 Answers

The second statement in a for loop declaration is the condition under which the loop should be continued. Compare to the (hopefully familiar) construct:

for (let i = 0; i < 5; i++) {
  //            ^^^^^
}

In the above code, as long as i < 5 is true, the loop will continue.

Similarly, in your code, as long as the node variable is truthy, the loop will continue. As soon as the node stops being truthy (due to the node = node.rest done at the end of an iteration), the loop will stop.

Your code is equivalent to:

function listToArray(list) {
    let arr = [];
    let node = list;
    while (node) {
      arr.push(node.value);
      node = node.rest;
    }
    return arr;
}
Related