The In operator in JavaScript checks for property in specified object. If property is not found in object, it checks for it’s prototype chain. If it is found, it returns true. Else returns false.

Syntax

result = property in object;

Example of the IN property in protoype

The standard properties of object (example toString() … etc) and, properties created using Object.prototype can be tested to be present using for/in. The object standard properties and user defined  Object.prototype.properties  are nonenumerable, so they do not get displayed with  for/in loop but will return true when used with in loop. The user-defined object properties are enumerable. They are displayed in for/in loop.

Example of FOR / IN loop in JavaScript

Object obj is stored as maps, with country as index and capital as value. We can loop through the values using for/ in operator. When we add a Object.prototype.parameter to the map as in Object.prototype.show = "NoCountry"; and loop through for/in all the map values are displayed. The parameter added through prototype is also displayed through it is not in list. 

document.write(name); -> India Poland USA show

The object properties such as toString does not get displayed in list but In confirms it is present in object.

Object.defineProperty

We can use Object.defineProperty() to define the type of prototype property. We set or reset the boolean  to enumerate the property.

Syntax

Object.defineProperty(Object.prototype, “property_name”, {enumerable:true, value:”property_value”});

The enumerable value defines the property to be displayed in for/in or not.

Example of Object.defineProperty()

Object.defineProperty(Object.prototype, "show", {enumerable: false, value:"NoCountry" });

Using this to create the show property in example above, displays the object list as:

document.write(name); -> India Poland USA

Object.hasOwnProperty

The Object.hasOwnProperty determines if the property in for/in loop is Object’s default property or user defined property.

Example of Object.hasOwnProperty

// returns false

 document.write("has own property" + (obj.hasOwnProperty("toString")));

//returns true

document.write("has own property" + (obj.hasOwnProperty("India")));

 

›› go to examples ››