What does the following javascript do?
var groups = countrylist.split(',');
for( var i = -1, group; group = groupsCounty[++i]; ){
...
}
What does the following javascript do?
var groups = countrylist.split(',');
for( var i = -1, group; group = groupsCounty[++i]; ){
...
}
It's iterating over the elements of groups using the presence of a value in group as the guard condition. i.e.using JavaScript Truthiness to control the number of times the loop iterates, because guard will be false when there is no value that can be assigned to it.
The for
loop walks through the groups
array until groupsCounty[++i]
returns a falsely value.
With usage of the following terms:
for (<initial-expression>; <condition>; <final-expression>)
The initial-expression var i = -1, group
declares the variables i
and group
. For each iteration the looping condition group = groupsCounty[++i]
assignes the next array value to group
. If that expression is falsely (e.g. groupsCounty[++i]
returns undefined when out of bounds), the loop stops. And the final-expression is empty as i
is already increased within the contition expression.
With i starting at -1
increase i by 1
get the ith element from the groupsCounty array
if there is no such element: stop
otherwise: assign it to group and carry on (with whatever "…" is)
It's an optimised version of:
for (var i = 0; i < groupsCounty.length; i++; ){
var group = groupsCounty[i];
…
}
It's equivalent to
for (var group in groupsCounty) {
...
}
With the added value of having access to the index (i
).
Its doing this:-
var groups = countrylist.split(',');
for( var i = 0; i < groups.length; i++ )
{
var group = groups[i]
...
}
The only real difference is that the above is far more common and more easily recognisable. You would not have posted the above code asking "What is this doing?".
The code you've posted is an example of clever developing but not necessarily good coding practice.