karavanjo karavanjo - 3 months ago 13
Javascript Question

How to identify the first iteration in a for..in loop

We have a loop like this:

for (var prop in obj) {
if (obj.hasOwnProperty(prop) {
// Here need operation only for first iteration (1)
// Other operations
}
}


How can we identify first iteration in (1)?

Answer

If you can, move it out of the loop:

do_one_time_thing();
for (var prop in obj) {
   if (obj.hasOwnProperty(prop)) {
      // Other operations
   }
}

Otherwise, set a flag, and lower it after the first iteration:

var first_iteration = true;
for (var prop in obj) {
   if (obj.hasOwnProperty(prop)) {
      if (first_iteration) {
          do_one_time_thing();
          first_iteration = false;
      }
      // Other operations
   }
}