What are some of the practical for in loop use cases in JavaScript? They're bad for arrays since they ignore undefined keys and return numerable properties of the array object. I've never seen them used in any production code. Have they been all but deprecated by developers?
-
1Use them when you need to iterate over an object to behave like a hash table. For example, when you get JSON back from a request, and you want to act on all the properties of an object when you are not sure _what_ those properties will exactly be. --- not at all deprecated. – Michael Berkowski Dec 04 '13 at 20:40
-
1`for in` is for objects, not arrays. – SLaks Dec 04 '13 at 20:41
-
Well, yeah it's not the best way to handle arrays, but I find it extremely useful for objects – tewathia Dec 04 '13 at 20:41
-
@MichaelBerkowski Now that I think about it, I have used them to iterate through JSONs – Lloyd Banks Dec 04 '13 at 20:47
-
Reflection. That's it for the most part – Benjamin Gruenbaum Dec 04 '13 at 20:56
3 Answers
They are best for iterating over Javascript or JSON objects, like {"foo":bar,"baz":boo}
, but not for arrays, see more here for more info about that.
They are best done like this:
var obj={"foo":bar,"baz":boo}
for(var key in obj){
//hasOwnProperty ensures that it exists and bad stuff doesn't happen with deleted properties
if(obj.hasOwnProperty(key)){
obj[key].doSomething();
}
}
Douglas Crockford has a very good page on this here. For arrays, they should never be used, but they are very useful for objects, especially if you don't know what order the keys will be in, or what keys will be there. For arrays, just do this
for(var i=0;i<array.length;i++){
//do some stuff
}
The MDN says:
Iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.
You may also check Exploring JavaScript for-in loops
var str = "hello!", spreadOut = "";
for (var index in str) {
(index > 0) && (spreadOut += " ")
spreadOut += str[index];
}
spreadOut; //"h e l l o !"
You may refer this thread where CMS has explained it:
The purpose of the for-in statement is to enumerate over object properties, this statement will go up in the prototype chain, enumerating also inherited properties, thing that sometimes is not desired.

- 1
- 1

- 168,305
- 31
- 280
- 331
It is useful for iterating objects where the iteration is not dependent on order. It is useful in a few ways.
The variable used in the for in statement is the key to the current value.
The shorthand notation can save a few characters in the .js file.
It can be more readable.

- 81,153
- 41
- 202
- 273