How do you check whether an object property is undefined in JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you check whether an object property is undefined in JavaScript?

message-square
0

To check whether an object property is undefined in JavaScript, test obj.prop === undefined or typeof obj.prop === "undefined", and use optional chaining (obj?.nested?.prop === undefined) when intermediate objects might be null or undefined. Keep in mind that a property evaluating to undefined is different from a property being absent on the object—use Object.hasOwn(obj, "prop") or the in operator when you need to distinguish a missing property from one explicitly set to undefined.


1. Checking Property Value Directly (=== undefined and Optional Chaining)

When you know obj is a non-nullish object and want to check if its property value is undefined, strict equality (=== undefined) is clear, safe against undeclared variables, and works cleanly with optional chaining (?.):

// Check whether a property evaluates to undefined (safe on nested/nullable paths)
function isPropertyUndefined(obj, propName) {
  if (obj === null || (typeof obj !== "object" && typeof obj !== "function")) {
    return true;
  }

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

  return obj?.[propName] === undefined;
}

// Example usage:
const profile = { name: "Amina", bio: undefined, address: null };

console.log(isPropertyUndefined(profile, "bio"));           // true (explicitly undefined)
console.log(isPropertyUndefined(profile, "age"));           // true (missing property)
console.log(isPropertyUndefined(profile, "name"));          // false
console.log(profile?.address?.city === undefined);          // true (safe on null intermediate)
  • Strict equality (=== undefined): Avoids matching null, false, 0, or "", which loose equality (== undefined) would treat like undefined.
  • Safe on properties: Unlike an undeclared variable, reading a missing property on an object returns undefined instead of throwing a ReferenceError.

2. Distinguishing undefined Values from Missing Properties (Object.hasOwn and in)

An object can have a key whose value is literally undefined ({ a: undefined }) versus omitting the key altogether ({}), both of which evaluate to undefined via dot or bracket lookup:

// Distinguish between an existing property set to undefined and a missing property
function inspectPropertyPresence(obj, propName) {
  if (obj === null || (typeof obj !== "object" && typeof obj !== "function")) {
    return { existsOwn: false, inPrototypeChain: false, valueIsUndefined: true };
  }

  return {
    existsOwn: Object.hasOwn(obj, propName),
    inPrototypeChain: propName in obj,
    valueIsUndefined: obj[propName] === undefined
  };
}

// Example usage:
const record = { explicitUndefined: undefined };

console.log(inspectPropertyPresence(record, "explicitUndefined"));
// { existsOwn: true, inPrototypeChain: true, valueIsUndefined: true }

console.log(inspectPropertyPresence(record, "missingKey"));
// { existsOwn: false, inPrototypeChain: false, valueIsUndefined: true }
  • Object.hasOwn(obj, key): Checks only the object’s own properties (safer than obj.hasOwnProperty(key) on objects with null prototypes or custom hasOwnProperty keys).
  • key in obj: Checks both own and inherited properties along the prototype chain (such as "toString" in {} being true).

3. Handling null vs. undefined and typeof Guards

When validating inputs or optional fields, be careful not to confuse undefined with null, or assume a property check means the value is usable without narrowing:

// Checking undefined vs. nullish (undefined or null)
const config = { timeout: undefined, retryDelay: null, retries: 0 };

console.log(config.timeout === undefined);                 // true
console.log(config.retryDelay === undefined);              // false (it is null)
console.log((config.retryDelay ?? 1000) === 1000);         // true (nullish coalescing handles both)
  • Nullish vs. undefined: Use === undefined when null is a valid distinct value, and use == null or ?? when treating null and undefined alike.
  • Avoid void 0 clutter: === undefined is standard and readable in modern JavaScript; typeof is mostly helpful when checking an identifier that might not even be declared in scope.

TL;DR: Check obj.prop === undefined (or obj?.prop === undefined for nullable/nested objects) to test if a property’s value is undefined, and combine it with Object.hasOwn(obj, "prop") or "prop" in obj when you need to tell an explicit undefined value apart from a missing key.