Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript for loop with object instead of counter?

Looking at this piece of code:

for (var i = 0, f; f = families[i]; i++) {
}

I haven't actually seen a loop like this before and I want to be sure I understand it correctly.
Am I correct in assuming that if families.length == 2 that the 2nd part of the for line would return false on f = families[2]?

I would have thought it would need to be something like f == families[2] in order to return false.

like image 462
James P. Wright Avatar asked Sep 17 '11 00:09

James P. Wright


1 Answers

f = families[i] is an expression that returns the value of families[i]. (It also has the side-effect of assigning that value to f)

If families.length === 2 then families[2] === undefined thus the expression returns undefined which is falsey and breaks the loop.

For more hacking fun you can turn

for (var i = 0, f; f = families[i]; i++) {
  // body
}

into

for (var i = 0, f; f = families[i++]; /* body */);

You may have to string replace ; with , and string replace i with i-1. You also just murdered readability.

It should also be pointed out that the for loop is silly for readability.

Object.keys(families).forEach(function(key) {
  var family = families[key];
  /* body */
});

Is significantly more readable.

like image 53
Raynos Avatar answered Oct 26 '22 16:10

Raynos