Search code examples
javascriptpropertiesprototype

hasOwnProperty('getTime') returns false on date object


const test = new Date()
test.hasOwnProperty('getTime') // false
'getTime' in test // true

this means that getTime is not in the prototype of test (not it's own prototype), but further up the hierarchy (because in works). Why is that, I cannot find a reference explaining this. Is this due to how the getTime "property" is defined?


Solution

  • hasOwnProperty doesn't look up the prototype chain:

    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. (source)

    This is why hasOwnProperty is often used to check if a property exists, in for...in loops:

    for (key in obj) {
      if (obj.hasOwnProperty(key))
        // do stuff with obj[key]
      }
    }