What Is Property in Hasownproperty in JavaScript

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 in JavaScript

hasOwnProperty is a normal JavaScript function that takes a string argument.

When you call shape1.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).

You need to call hasOwnProperty with a string containing name, like this: shape1.hasOwnProperty("name").

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

hasOwnProperty with more than one property

There are two things going on here.

First, hasOwnProperty only takes one argument. So it'll ignore whatever other arguments you pass to it.

Second, (and I'm simplifying slightly here) it's going to convert that first argument to a String, and then check to see if the object has that property.

So let's look at your test cases:

The reason { "a": 1, "b": 2 }.hasOwnProperty( "a", "b"); returns true is because it's ignoring the second argument. So really it's just checking for "a".

{ "a": 1, "b": 2 }.hasOwnProperty( ["a", "b"]) returns false because the first argument, ["a", "b"], gets converted to "a,b", and there's no { "a": 1, "b": 2 }["a,b"].

To find out if a given object has all the properties in an array, you can loop over the array and check each property, like so:

function hasAllProperties(obj, props) {
for (var i = 0; i < props.length; i++) {
if (!obj.hasOwnProperty(props[i]))
return false;
}
return true;
}

Or, if you're feeling fancy, you can use the every function to do this implicitly:

var props = ["a", "b"];
var obj = { "a": 1, "b": 2 };
var hasAll = props.every(prop => obj.hasOwnProperty(prop));

I hope that helps clarify things. Good luck!

Javascript object.hasOwnProperty() vs Reflect.has()

One major difference is that Reflect.has will check whether any of the object's internal prototypes have the key, whereas hasOwnProperty only checks whether the object itself has the key:

const proto = { foo: 'foo' };const obj = Object.create(proto);console.log(Reflect.has(obj, 'foo'));console.log(obj.hasOwnProperty('foo'));

Object.hasOwn() vs Object.prototype.hasOwnProperty()

Using Object.hasOwn() as a replacement for Object.hasOwnProperty()

Object.hasOwn() is intended as a replacement for Object.hasOwnProperty() and is a new method available to use (yet still not fully supported by all browsers like safari yet but soon will be)

Object.hasOwn() is a static method which returns true if the specified object has the specified property as its own property. If the property is inherited, or does not exist, the method returns false.

const person = { name: 'John' };
console.log(Object.hasOwn(person, 'name'));// true
console.log(Object.hasOwn(person, 'age'));// false

console.log(person.hasOwnProperty('name'));// true
console.log(person.hasOwnProperty('age'));// false

const person2 = Object.create({gender: 'male'});
console.log(Object.hasOwn(person2, 'gender')); // false
console.log(person.hasOwnProperty('gender')); //false

// gender is not an own property of person, it exist on the person2 prototype

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.

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

Which object does not have `hasOwnProperty` in JavaScript?

TLDR;

Object.prototype.hasOwnProperty can be called directly on

  • Object.prototype,

  • The subset of objects which have Object.prototype in their inheritance chain and don't redefine hasOwnProperty in either the inheritance chain or on the object, and

  • BigInt, Boolean, Number, String and Symbol primitive values. Calling it on primitive values is generally superfluous however as

      (primitiveValue).hasOwnProperty(propertyName)

    always rerturns false - primitive values do not have own properties.


Data Types

JavaScript currently supports eight different data types in the ECMAScript 2020 specification:

BigInt (introduced in ECMAScript 2020), Boolean, Null, Undefined, Number, String, Symbol (new in ECMAScript 2015)

and Object.

The first seven of these are primitive values rather than object values - including null which is of data type Null. (Yes, typeof null returns "object" instead of "null", but this is an artifact of early JavaScript engine design that can't be fixed because it would break the web.)

Number, Boolean and String

Values of type Number, Boolean and String are automatically converted into "wrapper" object instances of global constructors Number, Boolean and String respectively when used with property value lookup syntax.

Hence

(1).hasOwnProperty("MAX_SAFE_INTEGER")

returns false because the property is inherited from Number.prototype. Similarly hasOwnProperty calls on Boolean values return false because Boolean wrapper objects don't have any innate own properties themselves. But

("hello folks").hasOwnProperty("length");

returnstrue because "length" is an own property of the String wrapper object.

Undefined and Null

Primitive values of data type Undefined (undefined) or Null (null) are not converted to wrapper objects and generate syntax errors when attempting to call hasOwnProperty on them as a method:

    (undefined).hasOwnProperty("example")  // TypeError
(null).hasOwnProperty("example") // TypeError

Symbol and BigInt

Symbol and BigInt data type values have separate treatment - they were both introduced following a decision that new data types in ECMAScript would not have object wrappers.

Effectively this means that the JavaScript engine internally implements the syntax of applying Symbol.prototype and BigInt.prototype methods to symbol and bigint data types respectively, but only allows read access to prototyped methods and properties - any attempt to set a property on a symbol or bigint data type generates an error.

  • Neither the Symbol nor BigInt global functions allow the use of new before calls to them.

  • Symbol acts a factory function and returns a new symbol value.

  • BigInt is a type conversion function to convert strings and numbers to bigint data type.

  • Unlike older object wrappers for boolean, number and string data types, attempting to set properties on a symbol or bigint data type never quietly succeeds.

Object

Objects ( of data type Object) generally inherit hasOwnProperty from Object.prototype. This inheritance can fail if either hasOwnProperty is redefined somewhere later in the inheritance chain (not a good idea), or if the object was created with null in its inheritance chain before reaching Object.prototype.

The easiest way to create an object with null at the start of its inheritance chain is by calling

Object.create( null);

Extending such an object will also create objects which don't inherit from Object.prototype and so can't use hasOwnProperty.

Note that applying instanceof Object to an object whose prototype chain does not include Object.prototype returns false. Do not use instanceof to determine Object data type.

Wrapper objects and strict mode.

In early versions of JavaScript, setting properties on wrapper objects automatically created from primitive values was syntactically correct and did not generate errors. However, the wrapper object was discarded as soon as the wrapper object expression was evaluated. Trying to look up a custom property in later code fails because a new, different wrapper object, lacking the custom property, is used for the lookup.

Strict mode generates an error if an attempt is made to assign a property value to any primitive value.

Possible Check Function

const checkOwnProperty = (obj, propertyName) =>
(obj && (typeof obj == "object" || typeof obj == "function") &&
Object.prototype.hasOwnProperty.call( obj, propertyName))
? true : false;

// Test:
var o = {name: "foo"};
console.log ( "name " + checkOwnProperty( o, "name"))
console.log ( "foo " + checkOwnProperty( o, "foo"))
console.log ( "0 " + checkOwnProperty( 0, "foo"))

hasOwnProperty() is only checking if a certain property exists in a JSON, but doesn't return anything if it doesn't

The issue is that in the response data['features'] is empty. When iterating over an empty array, nothing within the for...of loop is executed.

const emptyArray = [];
for (const item of emptyArray) {
// body is never executed...
}

If just checking the presence of an item within data['features'] is enough, you could use the length of the array.

function appendData3(data) {
if (data.features.length > 0) {
console.log("TRUE");
} else {
console.log("FALSE");
}
}

To check if one of the elements has the property "attributes" you could use some():

function appendData3(data) {
if (data.features.some(item => item.hasOwnProperty("attributes"))) {
console.log("TRUE");
} else {
console.log("FALSE");
}
}


Related Topics



Leave a reply



Submit