Object.prototype.hasOwnProperty.call shortcut providing safe property existence checking
npx @tessl/cli install tessl/npm-has@1.0.0hasObject.prototype.hasOwnProperty.call()hasOwnPropertynpm install hasvar has = require('has');Note: This package only supports CommonJS (no ESM support).
var has = require('has');
// Check if an object has its own property
has({}, 'hasOwnProperty'); // false
has(Object.prototype, 'hasOwnProperty'); // true
// Safe property checking for objects that may lack hasOwnProperty
var obj = Object.create(null);
obj.foo = 'bar';
has(obj, 'foo'); // true
has(obj, 'hasOwnProperty'); // false
// Works safely with all object types
var arr = [1, 2, 3];
has(arr, 'length'); // true
has(arr, '0'); // true
has(arr, 'push'); // false (inherited method)Safe property ownership checking that works with all object types, including those with overridden
hasOwnProperty/**
* Safely checks if an object has its own property
* @param {Object} O - The object to check for property ownership
* @param {string|symbol} P - The property name to check
* @returns {boolean} true if object has own property, false otherwise
* @throws {TypeError} when object is null or undefined
*/
function has(O, P);Usage Examples:
var has = require('has');
// Standard objects
has({ name: 'John' }, 'name'); // true
has({ name: 'John' }, 'toString'); // false (inherited)
// Objects with overridden hasOwnProperty
var obj = { hasOwnProperty: 'not a function' };
obj.name = 'test';
has(obj, 'name'); // true (safe)
// Objects created with null prototype
var nullObj = Object.create(null);
nullObj.prop = 'value';
has(nullObj, 'prop'); // true
// Arrays and array-like objects
has(['a', 'b'], '0'); // true
has(['a', 'b'], 'length'); // true
has(['a', 'b'], 'push'); // false
// Error cases
has(null, 'prop'); // throws TypeError
has(undefined, 'prop'); // throws TypeErrorThe function throws a
TypeErrornullundefinedhasOwnPropertytry {
has(null, 'property');
} catch (error) {
console.log(error instanceof TypeError); // true
}
try {
has(undefined, 'property');
} catch (error) {
console.log(error instanceof TypeError); // true
}The function uses
Function.prototype.call.bind()For TypeScript users, the function signature is effectively:
function has(O: any, P: string | symbol): boolean;Note: This package does not include TypeScript definitions. Consider using
@types/has