brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Object.hasOwn(obj, key) replaces obj.hasOwnProperty(key)

Web-Development
~/tips/tip-javascript-object-hasown

const foo = Object.create(null);

Checks whether an object has its own key, even for objects without a prototype.

Checking whether an object has a key of its own looks simple until the object came from JSON.parse() or from user input. Object.hasOwn() is the safer way to ask. I’d switch to it in any new code.

The old way was obj.hasOwnProperty("key"). It breaks in two cases. Objects created with Object.create(null) have no such method, and an object can shadow the method with a property of its own name:

const foo = Object.create(null);
foo.prop = "exists";

foo.hasOwnProperty("prop"); // TypeError: not a function
Object.hasOwn(foo, "prop"); // true
const bar = { hasOwnProperty() { return false; }, id: 1 };

bar.hasOwnProperty("id");  // false, wrong
Object.hasOwn(bar, "id");  // true

That second case matters when keys come from outside. If a JSON body contains a field named hasOwnProperty, the old check can give a wrong answer, and a wrong answer in a permission or validation check is how bugs turn into security issues.

The check only looks at the object itself, not the prototype chain, unlike the in operator:

const o = { a: 1 };
Object.hasOwn(o, "a");        // true
Object.hasOwn(o, "toString"); // false, inherited
"toString" in o;              // true

One caveat: it returns true for an own property whose value is undefined or null, so it tells you the key exists, not that it has a useful value. If you want a default for missing values, use ?? instead.

It has been in all major browsers since March 2022. Before that, Object.prototype.hasOwnProperty.call(obj, key) was the workaround.

Further reading: MDN: Object.hasOwn()

More Web-Development tips ab -n 200 -c 10 https://example.com/ console.assert(items.length > 0, 'cart is empty', items) document.designMode = "on" function save(item) { Save draft All Web-Development tips (67) All topics

Link