For..In and Hasownproperty

for..in and hasOwnProperty

Because if you don't, it will loop through every property on the prototype chain, including ones that you don't know about (that were possibly added by somebody messing with native object prototypes).

This way you're guaranteed only the keys that are on that object instance itself.

Should hasOwnProperty still be used with for..in statements

If you're creating a basic object with {}, or getting it from JSON using JSON.parse, then hasOwnProperty is globally useless.

But if you're extending a "class" (using prototype), then it helps you to know if you're accessing your "own properties" (direct properties, including direct functions).

Note that a basic object has at least one (not direct) property, that you may discover with console.log({}); or console.log({}.toString) but it's not enumerable and not seen in a for... in loop :

A for...in loop does not iterate over non–enumerable properties.
Objects created from built–in constructors like Array and Object have
inherited non–enumerable properties from Object.prototype and
String.prototype that are not enumerable, such as String's indexOf
method or Object's toString method. The loop will iterate over all
enumerable properties of the object or that it inherits from its
constructor's prototype (including any which overwrite built-in
properties).

When do I need to use hasOwnProperty()?

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
});

what's the difference with hasOwnProperty and in?

Example:

var o = { 'foo': 'bar' };

console.log('constructor' in o); // TRUE
console.log('foo' in o); // TRUE

console.log(o.hasOwnProperty('constructor')); // FALSE
console.log(o.hasOwnProperty('foo')); // TRUE

hasOwnProperty

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

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; unlike the in operator, this method does not check down the object's prototype chain.

in

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in

The in operator returns true if the specified property is in the specified object.

What is property in hasOwnProperty in JavaScript?

hasOwnProperty returns a boolean value indicating whether the object on which you are calling it has a property with the name of the argument. For example:

var x = {
y: 10
};
console.log(x.hasOwnProperty("y")); //true
console.log(x.hasOwnProperty("z")); //false

However, it does not look at the prototype chain of the object.

It's useful to use it when you enumerate the properties of an object with the for...in construct.

If you want to see the full details, the ES5 specification is, as always, a good place to look.

hasOwnProperty & Object.keys in javascript not working as expected

The name, age, etc., properties on teacher1 are own properties. They are not inherited from teacher1's prototype (Teacher.prototype) or its prototype (Person.prototype). Although it's Person that assigns them, they're still own properties. this in the call to Person from Teacher is the object that will be assigned to teacher1, so

this.age = age;

...makes age an own property of teacher1.

Once the property has been created on the object, there's no way to know what function (if any) created it.


There are a couple of other problems with your code:

  1. You're assigning an arrow function to Teacher.prototype.greeting. Don't use arrow functions for methods that will be inherited, this won't be set correctly. A couple of related questions whose answers may be useful:

    • Methods in ES6 objects: using arrow functions
    • What's the meaning of “=>” (an arrow formed from equals & greater than) in JavaScript?
  2. You're assigning to Teacher.prototype.greeting, then later replacing Teacher.prototype entirely (Teacher.prototype = Object.create(Person.prototype);). So you won't have the greeting method on it.

  3. If you replace the object on Teacher.prototype the way you are, it's important to make sure its constructor property is correct:

    Teacher.prototype = Object.create(Person.prototype);
    Teacher.prototype.constructor = Teacher; // <===

But: Since you're using ES2015+ features anyway (arrow functions, template literals, ...), you can make this all much simpler by using class syntax.

Is there a benefit to use hasOwnProperty() when iterating through object keys in JavaScript

The docs indicate that:

The hasOwnProperty() method returns a boolean indicating whether the
object has the specified property as own (not inherited) property.

The hasOwnProperty method ensure that the property you are checking is directly on an instance of an object but not inherited from its prototype chain. If you don't check, it will loop through every property on the prototype chain.

const obj = {
prop1: [],
prop2: {},
prop3: "",
prop4: 0,
prop5: null,
prop6: undefined
}

obj.prototype = {foo: 'bar'};

P/s: NOTE that:

JavaScript does not protect the property name hasOwnProperty; thus, if the possibility exists that an object might have a property with this name, it is necessary to use an external hasOwnProperty to get correct results:

var foo = {
hasOwnProperty: function() {
return false;
},
bar: 'Here be dragons'
};

foo.hasOwnProperty('bar'); // always returns false

So you need to use:

Object.prototype.hasOwnProperty.call(foo, 'bar');

Why does Typescript treat `object.hasOwnProperty(key)` as essentially different from `key in object`

In the issue microsoft/TypeScript#10485, it was suggested for the in operator to act as a type guard which can be used to filter unions; this was implemented in microsoft/TypeScript#15256 and released with TypeScript 2.7.

This was not done for Object.prototype.hasOwnProperty(); if you really feel strongly about this, you might want to file a suggestion for it, noting that a similar suggestion (microsoft/TypeScript#18282) was declined because it was asking for the more controversial narrowing of the key and not the object... and some people have wanted both (microsoft/TypeScript#20363). And there's no guarantee the suggestion would be accepted.

Luckily for you, though, you don't have to wait for this to be implemented upstream. Unlike an operator like in, the hasProperty() method is just a library signature that can be altered to act as a user-defined type guard function. What's more, you don't even have to touch the standard library definition; you can use declaration merging to augment the Object interface with your own signature for hasOwnProperty():

// declare global { // need this declaration if in a module
interface Object {
hasOwnProperty<K extends PropertyKey>(key: K): this is Record<K, unknown>;
}
// } // need this declaration if in a module

This definition says that when you check obj.hasOwnProperty("someLiteralKey"), a true result implies that obj is assignable to {someLiteralKey: unknown}, while a false result does not. This definition might not be perfect and there are probably quite a few edge cases (e.g., what should obj.hasOwnProperty(Math.random()<0.5?"foo":"bar") imply? what should obj.hasOwnProperty("foo"+"bar") imply? they will do weird things) but it works for your example:

const totalIn = ("total" in action) ? action.total : defavlt; // okay
const totalOwnProp = (action.hasOwnProperty("total")) ? action.total : defavlt; // okay

Okay, hope that helps; good luck!

Link to code

Why use Object.prototype.hasOwnProperty.call(myObj, prop) instead of myObj.hasOwnProperty(prop)?

Is there any practical difference [between my examples]?

The user may have a JavaScript object created with Object.create(null), which will have a null [[Prototype]] chain, and therefore won't have hasOwnProperty() available on it. Using your second form would fail to work for this reason.

It's also a safer reference to Object.prototype.hasOwnProperty() (and also shorter).

You can imagine someone may have done...

var someObject = {
hasOwnProperty: function(lol) {
return true;
}
};

Which would make a hasProp(someObject) fail had it been implemented like your second example (it would find that method directly on the object and invoke that, instead of being delegated to Object.prototype.hasOwnProperty).

But it's less likely someone will have overridden the Object.prototype.hasOwnProperty reference.

And since we are at it, why do we define this function at all?

See above.

Is it
just a question of shortcuts and local caching of property access for
(slight) performance gains...

It may make it quicker in theory, as the [[Prototype]] chain doesn't have to be followed, but I suspect this to be negligible and not the reason the implementation is why it is.

... or am I missing any cases where
hasOwnProperty might be used on objects which don't have this method?

hasOwnProperty() exists on Object.prototype, but can be overridden. Every native JavaScript object (but host objects are not guaranteed to follow this, see RobG's in-depth explanation) has Object.prototype as its last object on the chain before null (except of course for the object returned by Object.create(null)).



Related Topics



Leave a reply



Submit