Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixing "Do not access Object.prototype method 'hasOwnProperty' from target object" error

Based on hasOwnProperty() method docs I wrote the following:

const myObj = {
  prop1: 'val1',
  prop2: 'val2'
}

if (!myObj.hasOwnProperty('prop3')) {
  myObj.prop3 = 'val3'
}

But I'm getting this error:

Do not access Object.prototype method 'hasOwnProperty' from target object

Why does it not work if it's the same as in the docs, and how to fix it?

like image 998
drake035 Avatar asked Jan 19 '26 11:01

drake035


1 Answers

Use the static Object.hasOwn() instead:

const myObj = {
  prop1: 'val1',
  prop2: 'val2'
}

if (!Object.hasOwn(myObj, 'prop3')) {
  myObj.prop3 = 'val3'
}

console.log(Object.keys(myObj)); //returns [ 'prop1', 'prop2', 'prop3' ]
console.log(myObj.prop3); //returns val3

Object.hasOwn() is intended as replacement for Object.prototype.hasOwnProperty() HasOwn

like image 110
Garima Saxena Avatar answered Jan 21 '26 01:01

Garima Saxena



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!