JavaScript - Using the for-in loop

javascript

// JavaScript - Using the for-in loop:

The for-in loop:
for (variable name in object){
  ...
}
is used to iterate over properties of an object.  In each repetition, one 
property from the object is associated to the variable name, and the loop is 
continued till all the properties of the object has been processed.

It is usually necessary to test use object.hasOwnProperty(variable) to determine 
whether the property name is truly a member of the object or was found instead 
on the prototype chain.

for (myvar in obj) {
  if (obj.hasOwnProperty(myvar)) {
    ...
  }
}

// Counting the number of elements in an associative array:

Object.keys(counterArray).length

We can also calculate the length of an object by iterating through an object 
and by counting the object's own property. 

function getSize(object){
  var count = 0;
  for(key in object){
    // hasOwnProperty method check own property of object
    if(object.hasOwnProperty(key)) count++;
  }
  return count;
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License