A javascript object may contain several properties, at times we need to iterate those properties. for..in loop comes handy in this case, consider this:

<script type='text/javascript'>
var data =
        "name": "John",
        "age": "25",
        "active": "yes"

 //iterates through properties of data        
 for (var key in data) {
  if (data.hasOwnProperty(key)) {
        alert(key + " -> " + data[key]);

//alerts name -> John,age -> 25,active -> yes

"hasOwnProperty" method used to check whether "key" is an actual property of data and not come from the prototype of the given object. Didn't get a clear idea?

Yes, in javascript, an object can have both key-value pairs and other meta information. for..in iterates through all of them. Using hasOwnProperty method filters those items.


Comments (0)
Leave a Comment

loader Posting your comment...