How does this for loop condition work?
eloquent, for-loop, javascript, loops
Solution
First we can write the program in a different way it will be more understandable
function listToArray(list) {
array = [];
for (var i=list;i; i = i.rest)
{
array.push(i.value);
alert(array)
}
}
var listobject = { value: 10, rest: { value: 20, rest: { value: 30, rest: null } } };
listToArray(listobject);
Here listobject is an object literal and using the for loop we are traverse through the values of the object literal , or properties of object literal.
We can take each line of the code
1) `listToArray(listobject);`
this is the function call, here we are passing object as an argument to the function.
2)When this code executes then the control goes to the function definition
function listToArray(list) { ...}
Here the list is the same argument what we are passing at the time of function call.
3) `array = [];` inside the function we are declaring an array, initially the array has no elements.
4)next is our for loop. `for (var i=list;list; i = i.rest)`
inside loop first we assigning var i=list;
means we are assign all the property of the object list to i
That means we can access every property of object via `i`,
example:
i.value will result 10
5) next Condition statement here it is `i` and in your program it is node
all have same meaning in this case :
the condition will false when `i` is null, in your case `node` is null.
6)`i=i.rest`
it will give the property of the object or value of the object.
Example : `listobject.value will result 10`
listobject.rest.value will result 20
listobject.rest.rest.value will result 30
7) and finally `array.push(i.value);`
add the values to our array and in this our array contains 10,20,30
Problem
The code example below is from Eloquent Javascript Chapter 4 Exercise 4.3 (A List). Why does the for-loop in the code below stop with the middle condition in the for-loop being "node"? ``` function listToArray(list) { array = []; for (var node=list; node; node = node.rest) array.push(node.value); return array; } list = { value: 10, rest: { value: 20, rest: { value: 30, rest: null } } }; console.log(listToArray(list)); ```