0

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);
}
Rajesh
  • 24,354
  • 5
  • 48
  • 79
  • `feature` will always equal `features[i]`, and `i++` still increments. This should still loop over 3 times. – Drew Kennedy Oct 13 '16 at 12:28
  • Like any other `for` loop, `for(initialization; condition; final-expression)` – adeneo Oct 13 '16 at 12:28
  • When `i=3` features[i] will return `undefined` and that will break the loop – Rajesh Oct 13 '16 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. – Keith Oct 13 '16 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](http://stackoverflow.com/questions/3010840/loop-through-an-array-in-javascript) – Rajesh Oct 13 '16 at 12:45

2 Answers2

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.

Aaron
  • 24,009
  • 2
  • 33
  • 57
  • 1
    Thanks, I wouldn't have imagined that it could matter ! I edited my answer accordingly. – Aaron Oct 13 '16 at 13:22
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.

Rajesh
  • 24,354
  • 5
  • 48
  • 79