DEV Community

Mohd Ahshan Danish
Mohd Ahshan Danish

Posted on

Problem with for in

We have an instance of Obj1. This instance has attributes name and age. When we print obj1, it returns the instance properties of the object, only name and not the age. However, Obj1's prototype also has a property age, and that property is not directly accessible through the instance of obj1.

function obj1(){
    this.name= "myName";
}
obj1.prototype.age = 10;
const i = new obj1();
console.error(i);
// obj1 { name: 'myName' }
Enter fullscreen mode Exit fullscreen mode

but when we do for in.

for(let prop in i){
   console.error(prop); 
}
// name and age both property is present
Enter fullscreen mode Exit fullscreen mode

Problem with for in is that it returns not only instance property of object but also all properties it inherit through prototype.

Solution: we can use hasOwnProperty for instance property.

for(let prop in i){
    if(i.hasOwnProperty(prop)) console.error(prop); 
}
Enter fullscreen mode Exit fullscreen mode

I will be posting tricks I have been using in my journey.
So follow me on LinkedIn.

Top comments (0)