Understanding Enumeration in JavaScript

chessboard using javascript

In JavaScript an object can contain as many properties as it wants. There may be a requirement when we need to traverse through all the properties; so rather than manually reading the values of the properties we can make use of for-in loop to iterate over all the properties. By default all the properties in JavaScript are enumerable which means that they can be accessed using for-in loop.

Using for-in loop we can go through all the properties of an object one by one using a variable. For example:

var person={
name:"pixxstudios",
age:21
};

var prop;

for(prop in person){
console.log(prop+" > "+person[prop]);
}

‘prop’ will display the name of the property and person[prop] will output the value of the specified property. We use the bracket notation to retrieve the value of a property.

In case we need to save all the property names of an object in array without iterating through a loop we can use Object.keys() which was introduced in EMCAScript5.

var person={
name:"pixxstudios",
age:21
};

var allProp=Object.keys(person);

Next we can retrieve the property names and values using a for loop whenever we require.

var person={
name:"pixxstudios",
age:21
};

var allProp=Object.keys(person);
var l=allProp.length;
for(var i=0;i "+person[prop[i]]);
}

There are some differences between for-in loop and Object.keys() method of accessing properties and its values. One is that for-in loop enumerates prototype properties while Object.keys() gives only own properties. Differences between these two will be explained in another blog post.

Related Posts