How to use `hasOwn()` to check if an object has a specific property?

const transformer = {
  fraction: 'Autobots',
  hasOwnProperty() {
    return 'Decepticons!';
  },
};

// output: 'Decepticons'
console.log(transformer.hasOwnProperty('fraction'));
// output: true
console.log(Object.hasOwn(transformer, 'hasOwnProperty'));
Copy

August 5th, 2022

# Check if an object has a specific property

Add to bookmarks

A safe way to check if an object has a specific property, is to use Object.hasOwn. It is possible to do the same with Object.prototype.hasOwnProperty, but the problem is, that the object could have it's own proerty named hasOwnProperty.

HomeBookmarks