Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - what does this line do?

What does the following javascript do?

var groups = countrylist.split(',');    
for( var i = -1, group;  group = groupsCounty[++i]; ){
  ...
}
like image 470
digiguru Avatar asked Feb 12 '10 15:02

digiguru


4 Answers

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];
    …
}
like image 74
Quentin Avatar answered Sep 23 '22 22:09

Quentin


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.

like image 43
cmsjr Avatar answered Sep 23 '22 22:09

cmsjr


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.

like image 32
AnthonyWJones Avatar answered Sep 20 '22 22:09

AnthonyWJones


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.

like image 22
Gumbo Avatar answered Sep 23 '22 22:09

Gumbo