Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For In Loop Uses in JavaScript

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?

like image 942
Lloyd Banks Avatar asked Jan 23 '26 11:01

Lloyd Banks


1 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
}
like image 130
scrblnrd3 Avatar answered Jan 25 '26 01:01

scrblnrd3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!