1

I've been watching some courses and reading some lectures on JavaScript. I've seen that many web developers when they have an array or an object, to loop through it, they use the common for loop like this:

for (var i = 0; i < Things.length; i++) {
    Things[i]
}

where Things is an array or an object.

or this:

for (var i = Things.length; i--; ) {
    Things[i];
}

others makes it even more complicated by using this:

for (var i = Things.length - 1; i >= 0; i--) {
    Things[i]
}

and lately, I've found out that there's even a JQuery method to loop through arrays and objects:

$.each(Things, function (index,value){
   // some code
});

but why using these four, while we have a more direct for loop for arrays and object like the following:

for (var prop in Things) {
    Things[prop]
}

is there anything behind this common practice? performance issues? any browser compatibility issues? anything at all?

Alex C.
  • 4,021
  • 4
  • 21
  • 24
  • 1
    Well the second and third examples iterate through in reverse direction: so they are not the same (and the difference between those two is the extent of expected familiarity of the detailed semantics of the post-decrement operator). – Richard Jul 05 '15 at 08:45
  • Additionally `for…in` does not have the same sematics: (simplifying somewhat) if there are any non-numeric indexes then the indexed form will not use them, but the `for…in` will. And then you need to consider additional properties from the object's prototype, so remember to check via `hasOwnProperty`. – Richard Jul 05 '15 at 08:50
  • Just to be clear: A `for ... in` loop is **not** a _ for loop for arrays_. Not even close. I always wonder where people get this idea from. – a better oliver Jul 05 '15 at 11:17

0 Answers0