Jenny Jenny - 14 days ago 5
Javascript Question

listToArray Eloquent JavaScript

The book says:

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) {}


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.

Question 1: Could you explain how the condition of the for loop works? I understand that it is checking whether the node(the current list) is null.. but how does the "node" argument by itself work?

Question 2: why doesnt the following code work?

function listToArray(list){
var result = [];
while(list.value != null){
result.push(list.value);
list = list.rest;
}
return result;
};

console.log(listToArray(list));

Answer

To understand how this works, you need to know two things:

  • How java script For loop works.
  • What are truthy values.

The syntax for the for loop statement:

for ([initialization]; [condition]; [final-expression]) statement

[condition] An expression to be evaluated before each loop iteration. If this expression evaluates to true, statement is executed. If the expression evaluates to false, execution skips to the first expression following the for construct.

In Java script, a truthy value evaluates to true when evaluated in a Boolean context.

All values are truthy unless they are defined as falsy (i.e., except for false, 0, "", null, undefined, and NaN).

So till node is null at one point, we may say that node is truthy and evaluates to true.

When the statement, node = node.rest assigns a null value to node, there the for loop exits.

The below code does not work because, list.value may be undefined, or as a fact any other falsy value other than null.

function listToArray(list){
    var result = [];
    while(list.value != null){
        result.push(list.value);
        list = list.rest;
    }
    return result;
};

console.log(listToArray(list));

instead try, while(list.value).

Comments