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?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With