Object.hasOwn replaces hasOwnProperty
Use Object.hasOwn to check for own properties on null-prototype objects or data that shadows hasOwnProperty.
You count words into an object and guard each key with counts.hasOwnProperty(word). It worked until you switched the object to Object.create(null) to keep inherited keys out, and now the guard throws.
Two ways the method disappears
hasOwnProperty lives on Object.prototype. An object has it if its prototype chain reaches that prototype and nothing in front of it shadows the name.
const counts = Object.create(null)
counts.apples = 2
const parsed = JSON.parse('{"hasOwnProperty": 1, "id": 7}')
for (const [obj, key] of [[counts, 'apples'], [parsed, 'id']]) {
try {
obj.hasOwnProperty(key)
} catch (error) {
console.log(error.name) // TypeError, twice
}
}Each call throws on its own, because counts has no prototype and so no method to find. parsed has a key named hasOwnProperty, a number here, and that key hides the method. JSON from outside your code can carry that key.
The old guard for both is Object.prototype.hasOwnProperty.call(parsed, 'id'). The same form returns true for counts with 'apples'.
Ask the Object constructor
Object.hasOwn(obj, key) is a static function, so it does not depend on anything the object carries. It is part of ES2022.
Object.hasOwn(counts, 'apples') // true
Object.hasOwn(parsed, 'id') // true
Object.hasOwn(parsed, 'hasOwnProperty') // true
Object.hasOwn(parsed, 'toString') // false
'toString' in parsed // trueThe first three lines succeed on the objects that threw above, and the third finds the key that hid the method. The fourth is false because toString comes from the prototype, and the in operator on the last line returns true for the same reason.
Pick by intent. Use Object.hasOwn to ask whether the key is data on this object, and in when inherited keys count. It also accepts arrays and strings, so Object.hasOwn([10, 20], 1) and Object.hasOwn('abc', 'length') both return true.
The word counter, fixed
Swap the guard in the loop from the start.
const counts = Object.create(null)
for (const word of 'a b a c a b'.split(' ')) {
counts[word] = Object.hasOwn(counts, word) ? counts[word] + 1 : 1
}
console.log(counts)
// [Object: null prototype] { a: 3, b: 2, c: 1 }Node prints the counts and labels the object as having a null prototype.
To migrate, search for .hasOwnProperty( and hasOwnProperty.call(. Each x.hasOwnProperty(k) becomes Object.hasOwn(x, k), with the object first and the key second.
Object.hasOwn throws a TypeError for null and undefined. Check for those values first when the data may be missing.