Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping over an obj exercise

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:

  1. variable node is equal to the list object
  2. the length is equal to the node which is the same as the list object
  3. and node is equal to the value rest

Can someone break down what is happening in the this for loop in simple terms?

like image 892
Danniel Rolfe Avatar asked Jun 20 '26 18:06

Danniel Rolfe


1 Answers

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.

like image 151
Jim W says reinstate Monica Avatar answered Jun 23 '26 07:06

Jim W says reinstate Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!