6

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.

1
  • 1
    I'm intrigued, I assume that the loop won't stop till a certain criteria is met, not exactly when you process all the entries. Commented Sep 17, 2011 at 0:49

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

5 Comments

You also just murdered readability. Heh heh. Colonel Mustard in the observatory with the keyboard.
Indeed, but also per LEOPiC's comment, it's also possible that a falsey value somewhere in the middle of the array would cause the loop to break, not always necessarily when you hit the end...
@Funka since when is a family falsey ;)
The last example is not semantically the same; families could have additional properties attached (or not be a "real array"). But otherwise, +1.
@pst any competent programmer would make those additional properties non enumerable ;)
0

This looks like kind of a silly way of doing

for(var i in families) {
    if (families.hasOwnProperty(i)) {
        // do whatever you want with families[i]
        console.log(families[i]);
    }
}

2 Comments

This method doesn't make sense to me. Why use this versus a regular for loop? To me, the loop I posted is essentially taking out a line from a regular for loop where I would instantly say something like var family = families[i];
This is different ... families could have properties that are not 0..n, even if "own".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.