How do you safely check if an object has a specific own property in JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you safely check if an object has a specific own property in JavaScript?

message-square
0

To safely check if an object has a specific own property in JavaScript, call Object.hasOwn(obj, propKey) (preferred in modern environments, ES2022+) or Object.prototype.hasOwnProperty.call(obj, propKey) after verifying that obj is a non-nullish object or function. Unlike the in operator, these methods ignore inherited prototype properties (such as toString), and unlike calling obj.hasOwnProperty(key) directly, they will not throw or fail if obj was created with Object.create(null) or defines its own hasOwnProperty property.


1. Using Object.hasOwn() (Recommended Modern Approach)

Object.hasOwn(obj, key) checks only the object’s own properties and safely handles null-prototype objects as well as objects shadowing hasOwnProperty:

// Safely check if a value is a non-null object/function with its own specified key
function hasOwnPropSafely(target, propKey) {
  if (target === null || (typeof target !== "object" && typeof target !== "function")) {
    return false;
  }

  if (typeof propKey !== "string" && typeof propKey !== "symbol") {
    throw new TypeError("Expected propKey to be a string or symbol.");
  }

  return Object.hasOwn(target, propKey);
}

// Example usage:
const nullProtoDict = Object.create(null);
nullProtoDict.token = "abc123";

const customObj = { hasOwnProperty: "not a function", count: 0 };

console.log(hasOwnPropSafely(nullProtoDict, "token")); // true
console.log(hasOwnPropSafely(customObj, "count"));     // true
console.log(hasOwnPropSafely(customObj, "toString"));  // false (inherited, not own)
  • True even when value is undefined or null: Object.hasOwn({ a: undefined }, "a") returns true because the key exists as an own property.
  • Guard non-objects first: Passing null or undefined directly to Object.hasOwn() throws a TypeError, so check target !== null && (typeof target === "object" || typeof target === "function") first.

2. Using Object.prototype.hasOwnProperty.call() for Compatibility

When targeting older runtimes or transpilers that do not yet include Object.hasOwn, invoke hasOwnProperty via .call() on Object.prototype:

// Legacy-compatible own-property check using Function.prototype.call
function hasOwnPropLegacy(target, propKey) {
  if (target === null || (typeof target !== "object" && typeof target !== "function")) {
    return false;
  }

  return Object.prototype.hasOwnProperty.call(target, propKey);
}

// Example usage:
const protoObj = Object.create(null);
protoObj.enabled = false;

console.log(hasOwnPropLegacy(protoObj, "enabled")); // true
console.log(hasOwnPropLegacy(protoObj, "missing")); // false
  • Avoids obj.hasOwnProperty(key) pitfalls: Calling the method directly on obj fails if Object.create(null) has no Object.prototype or if an own property shadows hasOwnProperty.
  • Works with strings and symbols: Both Object.hasOwn() and Object.prototype.hasOwnProperty.call() accept string and Symbol keys.

3. Why in and Truthiness Checks Are Different

Using the in operator or a truthiness check (Boolean(obj[key])) answers a different question than checking for an own property:

// Comparing own-property check vs. "in" operator vs. truthiness
const item = { qty: 0, note: "" };

console.log(Object.hasOwn(item, "qty"));       // true  (own property)
console.log(Object.hasOwn(item, "toString"));  // false (inherited from Object.prototype)
console.log("toString" in item);               // true  ("in" walks the prototype chain)
console.log(Boolean(item.qty));                // false (0 is falsy even though "qty" exists)
  • in includes prototypes: "constructor" in {} or "valueOf" in {} returns true even though neither is an own property of {}.
  • Falsy values still exist: Properties with values like 0, "", false, null, or undefined are present on the object even when truthy checks evaluate to false.

TL;DR: Use Object.hasOwn(obj, key) (or Object.prototype.hasOwnProperty.call(obj, key) for older runtimes) after checking that obj is a non-null object/function—safely detecting own properties (even falsy or undefined ones) without prototype-chain false positives or Object.create(null) errors.