Javascript for loop with object instead of counter?

Looking at this piece of code:

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

I have not seen such a cycle before, and I want to be sure that I understand it correctly.
Do I correctly assume that if families.length == 2 , that the second part of the for string will return false on f = families[2] ?

I would think that to return false there should be something like f == families[2] .

+6
source share
2 answers

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

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

For more fun breaking you can turn

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

in

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

You may need to replace ; by , and replace line i with i-1 . You also just killed readability.

It should also be noted that the for loop is dumb for readability.

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

We read significantly.

+11
source

It looks like a dumb way to do

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

Source: https://habr.com/ru/post/897507/


All Articles