-1

There are two initialisation and no "x<y" to limit the iterations. So how does this loop work?

var features = [{
  position: new google.maps.LatLng(-33.91721, 151.22630),
  type: 'info'
}, {
  position: new google.maps.LatLng(-33.91539, 151.22820),
  type: 'info'
}, {
  position: new google.maps.LatLng(-33.91747, 151.22912),
  type: 'info'
}];
for (var i = 0, feature; feature = features[i]; i++) {
  addMarker(feature);
}
5
  • feature will always equal features[i], and i++ still increments. This should still loop over 3 times. Commented Oct 13, 2016 at 12:28
  • Like any other for loop, for(initialization; condition; final-expression) Commented Oct 13, 2016 at 12:28
  • When i=3 features[i] will return undefined and that will break the loop Commented Oct 13, 2016 at 12:29
  • Plenty of people with good answers here, but going forward a less confusing construct is of course. features.forEach(addMarker) , Of course you wanted to know why it worked, but for people browsing might be worth pointing out the forEach. Commented Oct 13, 2016 at 12:40
  • @Keith You are right that mentioning forEach or any other method would be out of scope. But for anyone who is looking for it, please refer Different ways to loop through array Commented Oct 13, 2016 at 12:45

2 Answers 2

2

Access to an out-of-bound index in Javascript will yield undefined, which is a falsey value. Once the index has got outside of the bound, the feature = features[i] assignment, which evaluates to the value it assigns, will be considered false and the loop will exit.

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

1 Comment

Thanks, I wouldn't have imagined that it could matter ! I edited my answer accordingly.
0

There is a shortcut where if you wish to assign and return same value, you can do return variable = value. This will return value

Sample

var x;
function notify(v){
  return x = v;
}

console.log(notify(10))

So in your code, when you do feature = features[3], since features[3] is undefined, it returns undefined which is falsey. Hence your loop breaks.

Sample

var x = 0;
if(x = 1){
  console.log('Success')
}
else{
  console.log('Error')
}

if(x = undefined){
  console.log('Success')
}
else{
  console.log('Error')
}

Note you loop will break if features[i] return 0 or false or undefined or any other falsey value. This is working fine in this case, but I would not recommend it.

Comments

Your Answer

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