🚧 App in Alpha. Features subject to change/break without notice.

EJ's Notebook - Quick Tip: `in` vs. `Object.hasOwn`

Quick Tip: `in` vs. `Object.hasOwn`

Posted Apr 4, 2025 | ~1 minute read

Here, we see two ways of checking for the existence of a certain property on an object: one which traverses the prototype chain and one which doesn't.

const cat = {
 get legsCount() {
  return 4
 }
}
const tabbyCat = Object.create(cat)
console.log("legsCount" in cat)
// true

console.log("legsCount" in tabbyCat)
// true

console.log(Object.hasOwn(cat, "legsCount"))
// true

console.log(Object.hasOwn(tabbyCat, "legsCount"))
// false

Be careful. Class prototypes have their own properties but class instances do not own those properties.

class CatClass {
 get legsCount() {
  return 4
 }
}
const catInstance = new CatClass()
console.log("legsCount" in CatClass.prototype)
// true

console.log("legsCount" in catInstance)
// true

console.log(Object.hasOwn(CatClass.prototype, "legsCount"))
// true

console.log(Object.hasOwn(catInstance, "legsCount"))
// false
609:12 AM