Grian

Grian

Using the new Object.hasOwn method in JavaScript

The Object.hasOwn() method is a new static method introduced in V8 9.4.

This is a method meant to replace the common pattern of writing code that looks like this:

Object.prototype.hasOwnProperty.call(object, "foo");

This pattern is usually done to make sure that the specified object actually has the property, as though every object inherits from the Object prototype, you can still override it when creating the object, or it simply doesn't exist when doing Object.create(null)

Using this method

This method is pretty simple to use, first create an object:

const foo = {
    bar: "hey", 
}

then call the method on it with the property:

console.log(Object.hasOwn(foo, "bar")); // logs true
console.log(Object.hasOwn(foo, "baz")); // logs false

This method will return false on inherited values:

console.log(Object.hasOwn({}, "toString")); // logs false

Compatibility

At this time the method is supported by all major browsers except Safari(although it's feature flagged in Firefox), it is also supported by both Node and Deno.

If you are targeting an older version of browsers, there's a simple polyfill provived by the TC39 Proposal, available here.

Linting

If you want to ensure your codebase is using this and not the old method, there is also a ESLint rule available that enforces usage of Object.hasOwn over Object.prototype.hasOwnProperty.call

It can be found here.

Relevant links and documentation