Ad

Never Seen For Loop This Way How Does This Work?

- 1 answer

I am just reading through a book but it didn't mention using for this way. The most common way I can understand but this I have no idea how it start and end.

this is a function which has a for loop in it and what's being inserted into the argument is an object which inherits objects and objects like a list.

function listToArray(list) {
  var array = [];
  for (var node = list; node; node = node.rest)
    array.push(node.value);
  return array;
}

var object = {
    value: 10,
    rest: {
        value: 20,
        rest: {
            value: 30,
            rest: null
        }
    }
}

console.log(listToArray(object));
// → [10, 20, 30]

for (var node = list; node; node = node.rest) this is the part where I don't understand how it works. How it start or end.

I just have a simple guess myself to start off, node is an object so if node != null then node = list and node = node.rest which is the next object

Ad

Answer

A for loop take three arguments:

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

var node = list; runs when the loop is started.

node is the condition, if it is false, the loop won't go around again.

node = node.rest is run at the end of the loop.

So:

It sets node to list and then keeps replacing node with the value of the previous nodes rest property.

Eventually node is { value: 30, rest: null }, so it sets node to null then tests if null is true and then stops because it isn't.

Ad
source: stackoverflow.com
Ad