I'm reading Eloquent Javascript by Marijn Haverbeke and I'm working on chapter 4's obj to array, and array to obj exercise. The solution to the array to obj is as follow:
var list = {value: 1, rest: { value: 2, rest: { value: 3, rest: null}}};
function listToArray(list){
var array = [];
for(var node = list; node; node = node.rest){
array.push(node.value);
}
return array;
}
console.log(listToArray(list));
I'm confused on what is happening on the for loop. This is what I do understand:
Can someone break down what is happening in the this for loop in simple terms?
for(var node = list; node; node = node.rest)
First part (up to first ;) means; initialize node by setting it to list;
Second part means; keep looping until 'node' is null. This is because the 2nd part is actually an expression, you often see something like i<list.length but it doesn't have to involve lengths, it just has to be a boolean, true means keep going and false means stop. In Javascript you can just put the object variable for the expression, it means the same as node!=null
Third part means; after each loop set node equal to the result of node.rest. Where node.rest is another object to work through.
So the first time it loops, this is what you get
node = {value: 1, rest: { value: 2, rest: { value: 3, rest: null}}}
and it will push node.value (which is 1) on to array.
Second time it loops you get;
node = { value: 2, rest: { value: 3, rest: null}}
and it will push node.value (which is 2) on to array.
And so on until node.rest is null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With