Enumeration in JavaScript

In the previous post, I mentioned that I would have talked about the ”FOR-IN loop” in this post, and that’s what I’m about to do. So reading the title, you can gather how “for-in” loop is used for Enumeration in JavaScript.

What does it mean?

It means that if you want to enumerate the properties inside a JavaScript object, you need to use this type of loop. This is an example:

1
2
3
4
5
6
7
// Object literal
var myObject = {
  field : "myfield",
  mymethod : function(){
      return "hello";
  }
}
1
2
3
4
// for-in loop
for (i in myObject) {
  console.log(i) //"field", "mymethod"
}

The console will print the properties of the object, so the field and the method.

Coming back to my previous post, one of the issue with this loop is that is taking under consideration even all the objects involved in the prototypal chain, so that if we augment the Object with a new property the for-in loop will consider even this last one.

1
2
3
4
5
6
7
8
9
10
11
12
13
Object.prototype.newMethod = "string";
// Object literal
var myObject = {
  field : "myfield",
  mymethod : function(){
      return "hello";
  }
}

// for-in loop
for (i in myObject) {
  console.log(i) //"field", "mymethod", "newMethod"
}

To avoid this inconvenient, we can use the method hasOwnProperty() which returns true if the property belongs to the object itself (not considering the prototype), so that:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Object.prototype.newMethod = "string";

// Object literal
var myObject = {
  field : "myfield",
  mymethod : function(){
      return "hello";
  }
}

// for-in loop
for (i in myObject) {
  if(myObject.hasOwnProperty(i)){
      console.log(i) //"field", "mymethod"
  }
}

In this case we get what we possibly were expecting!

In ECMAScript 5, few enhancements have been made and now you can define a property (Object.defineProperty method) and you can use the method Object.keys(obj) to return an array of the properties belonging to that object without the need of using the “dirty” hasOwnProperty(). That’s how you could rewrite the previous code in ECMAScript 5:

1
2
3
4
5
6
7
8
"use strict"
var myObject = {
  field : "myfield",
  mymethod : function(){
      return "hello";
  }
}
Object.keys(myObject); //["field", "mymethod"]

Comments