'When do I need to use hasOwnProperty()?

I read that we should always use hasOwnProperty when looping an object, because the object can be modified by something else to include some keys we don't want.

But is this always required? Are there situations where it's not needed? Is this required for local variables too?

function my(){
  var obj = { ... };
  for(var key in obj){
    if(obj.hasOwnProperty(key)){
      safe
    }
  }
}

I just don't like adding an extra if inside the loop if I don't have to.

Death to hasOwnProperty

This guy says I shouldn't use it at all any more.



Solution 1:[1]

Object.hasOwnProperty determines if the whole property is defined in the object itself or in the prototype chain.

In other words: do the so-called check if you want properties (either with data or functions) coming from no other place than the object itself.

For example:

function A() {
   this.x = "I'm an own property";
}

A.prototype.y = "I'm not an own property";

var instance = new A();
var xIsOwnProperty = instance.hasOwnProperty("x"); // true
var yIsOwnProperty = instance.hasOwnProperty("y"); // false

Do you want to avoid the whole check if you want own properties only?

Since ECMAScript 5.x, Object has a new function Object.keys which returns an array of strings where its items are the own properties from a given object:

var instance = new A();
// This won't contain "y" since it's in the prototype, so
// it's not an "own object property"
var ownPropertyNames = Object.keys(instance);

Also, since ECMAScript 5.x, Array.prototype has Array.prototype.forEach which let’s perform a for-each loop fluently:

Object.keys(instance).forEach(function(ownPropertyName) {
    // This function will be called for each found "own property", and
    // you don't need to do the instance.hasOwnProperty check any more
});

Solution 2:[2]

When you're using for (var key in obj) it will loop through the given object + its parent objects' properties on the prototype chain until it reaches the end of the chain. As you want to check only a specific object's properties, you need to use hasOwnProperty.

This is not needed in for (var i = 0; i < length; i++) or data.forEach().

Solution 3:[3]

YES, use it always with for ... in

There are some nice answers here describing what hasOwnProperty() does and offering other solutions.
But none do provide an answer to what this question and @João in comments asks.
Is this always required?

In other words, if the object is mine, if I have control over it, if the object is defined as my own local variable, do I still need to use hasOwnProperty()?

The complication with this question is, that the control over the variable of Object type is not what's important in this consideration.
What's important is the control over the Object type itself.

If the question is slightly rephrased to: "Is the use of hasOwnProperty() required if I have full control over the JS script, where it's used and everything in its or parent scopes?"
Then no, you don't need to use the hasOwnProperty(). But the full control over the environment is not something you should count on.

Consider this example

var variableCreatedByInocentUser = { amisane: 'yes' };
for (let key in variableCreatedByInocentUser) {
    console.log(key +'? '+ variableCreatedByInocentUser[key]);
}

console.log('-----');

Object.prototype.amicrazy = 'yes, you redefined Object type';

for (let key in variableCreatedByInocentUser) {
    console.log(key +'? '+ variableCreatedByInocentUser[key]);
}

console.log('-----');

for (let key in variableCreatedByInocentUser) {
    if (!variableCreatedByInocentUser.hasOwnProperty(key)) { continue; }
    console.log(key +'? '+ variableCreatedByInocentUser[key]);
}

It's fine to drop the hasOwnProperty() only until someone somewhere redefines the Object type. Before or even after your script is started.
The effect is retroactive. Even if you declared your variable "using original Object type", it does not work as expected in JS and the redefined Object type will also affect such variables created before.

Even though the redefining of base types is discouraged, it's being done in some frameworks. Such framework could be included and introduced into your global scope and break your script.
There might also be a safety issue. The Object could be redefined with malicious intention, making your loops perform additional tasks.

If you want to follow good practices, you should always consider all possible scenarios, like that the code you're writing could be reused or inserted, or joined with another project.

Use hasOwnProperty() even when it might seem not necessary and wasteful.

Solution 4:[4]

hasOwnProperty expects the property name as a string.

When you call Test.hasOwnProperty(name) you are passing it the value of the name variable (which doesn't exist), just as it would if you wrote alert(name).

Every object descended from Object inherits the hasOwnProperty method. This method can be used to determine whether an object has the specified property as a direct property of that object;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Peter Mortensen
Solution 2 Peter Mortensen
Solution 3 Finesse
Solution 4 Peter Mortensen