A more powerful hasOwnProperty

For a while now I started using NPM and publishing many small modules that do one thing, and do it well. One such module is the hasown package, which is a simple yet more powerful Object.hasOwnProperty replacement.

You usually use hasOwn with for loops, so here is a comparison between the tranditional method and the hasown module

1
2
3
4
5
6
//traditional use:
var obj = { firstName: '', lastName: ''}
for (var k in obj) if (obj.hasOwnProperty(k)){
console.log(obj[k])
}
1
2
3
4
5
6
7
8
9
var hasOwn = require('hasown')
var obj = { ... }
var objHasOwn = hasOwn(obj)
for (var k in obj) if (objHasOwn(k)){
console.log(k)
//or you can use if (hasOwn(obj, k))
}

So you can either use hasown with two arguments, the host object and a property name, or you can use the curried form. When you call hasown with one arg, it returns a function that accepts one parameter. When you call this function it returns a boolean depending of whether your bound object has the given property as an own property.

This is a really small module, but it makes code clearer and easier to read.