Question

Check Object Properties in JavaScript: hasOwn, in, and Object.hasOwn

Question

How can I check whether a JavaScript object contains a specific property?

For example:

const x = { key: 1 };

if (x.hasOwnProperty("key")) {
  // Do this
}

Are there other ways to perform this check, and when should each approach be used?

Short Answer

You will learn the difference between checking an object's own properties and checking properties that may be inherited through its prototype. You will also see why Object.hasOwn() is the modern, reliable choice for most own-property checks.

Concept

JavaScript objects store values under property names (also called keys). Before reading, updating, or validating a property, you may need to know whether it actually exists.

There are two important categories:

  • Own property: Defined directly on the object.
  • Inherited property: Available because the object inherits it from another object in its prototype chain.
const user = { name: "Ava" };

// `name` is an own property of user.

For most validation and data-processing tasks, you want to check for an own property. The recommended modern API is:

Object.hasOwn(user, "name"); // true

This matters because a property can exist with a falsy value such as false, 0, "", null, or undefined. A truthiness check does not tell you reliably whether the property exists.

Mental Model

Think of an object as a desk with labeled drawers.

  • An own property is a drawer physically built into that desk.
  • An inherited property is a drawer you can use because the desk follows a shared design from a parent model.

Object.hasOwn(object, key) asks: “Was this drawer built directly into this desk?”

key in object asks: “Can I access a drawer with this label, either on this desk or through its parent design?”

Take Quiz

Syntax and Examples

Use Object.hasOwn() when you need to know whether an object directly owns a property.

const product = {
  name: "Notebook",
  price: 5
};

console.log(Object.hasOwn(product, "name"));     // true
console.log(Object.hasOwn(product, "quantity")); // false

Object.hasOwn(object, propertyName) returns a Boolean:

  • true if propertyName is directly defined on object
  • false otherwise

Reading a property is not the same as checking for it

const settings = {
  darkMode: false
};

console.log(settings.darkMode);                  // false
console.log(Object.hasOwn(settings, "darkMode")); // true

The property exists even though its value is false.

Older compatible pattern

If you need to support environments without Object.hasOwn(), use:

const user = { id: 42 };

const hasId = Object.prototype.hasOwnProperty.call(user, "id");
console.log(hasId); // true

This is safer than calling user.hasOwnProperty("id") directly.

Step by Step Execution

Consider this example:

const profile = {
  username: "sam",
  subscribed: false
};

const hasSubscribedProperty = Object.hasOwn(profile, "subscribed");

if (hasSubscribedProperty) {
  console.log("Subscription preference was provided.");
}

Step by step:

  1. profile is created with two own properties: username and subscribed.
  2. Object.hasOwn(profile, "subscribed") checks the properties directly stored on profile.
  3. It finds subscribed, so it returns true.
  4. hasSubscribedProperty receives true.
  5. The if condition runs and logs the message.

The value of profile.subscribed is false, but that does not change the result. The check is about the property's presence, not whether its value is truthy.

Real World Use Cases

Property-existence checks are useful whenever input may be partial, optional, or controlled by another system.

  • API request validation: Check whether a client sent a field such as email before deciding whether to update it.
  • Partial updates: Distinguish “the user set enabled to false” from “the user did not send enabled.”
  • Configuration objects: Apply a default only when a configuration key is absent.
  • Form processing: Determine whether an optional form field was included.
  • JSON data processing: Safely handle records whose fields vary by source or version.

For example, preserving a deliberate false value during an update:

function updateSettings(current, updates) {
  if (Object.hasOwn(updates, "notifications")) {
    current.notifications = updates.notifications;
  }

  return current;
}

const settings = { notifications: true };
updateSettings(settings, { notifications: false });

console.log(settings.notifications); // false
Take Quiz

Real Codebase Usage

In production code, developers usually make property checks explicit at boundaries: API handlers, configuration loaders, and functions that accept external data.

Validate an input object

function createAccount(data) {
  if (!Object.hasOwn(data, "email")) {
    throw new Error("email is required");
  }

  return { email: data.email };
}

This guard clause stops the function early when required data is missing.

Apply defaults only when a key is absent

function getPageSize(options) {
  if (!Object.hasOwn(options, "pageSize")) {
    return 20;
  }

  return options.pageSize;
}

console.log(getPageSize({ pageSize: 0 })); // 0

Checking with Object.hasOwn() preserves intentional values such as 0.

Use in when inherited properties should count

Some framework objects expose behavior through prototypes. In that unusual case, use in intentionally:

const date = new Date();
console.log("toString" in date); // true

For plain JSON-like data, prefer own-property checks.

Common Mistakes

Using a truthiness check to test existence

This fails when a valid property contains a falsy value.

const options = { retries: 0 };

if (options.retries) {
  console.log("Property exists");
}

Nothing is logged because 0 is falsy, even though retries exists.

Use:

if (Object.hasOwn(options, "retries")) {
  console.log("Property exists");
}

Calling object.hasOwnProperty() directly

An object can contain its own property named hasOwnProperty, which replaces the inherited method.

const data = {
  hasOwnProperty: "not a function",
  id: 1
};

// data.hasOwnProperty("id"); // TypeError

Use Object.hasOwn(data, "id") instead.

Assuming every object inherits from Object.prototype

Objects created with Object.create(null) have no prototype, so they do not have a hasOwnProperty method.

const dictionary = Object.create(null);
dictionary.status = "ok";

console.log(Object.hasOwn(dictionary, "status")); // true

Using in when you only want direct properties

const item = {};
console.log("toString" in item); // true

toString is inherited. Use Object.hasOwn(item, "toString") when inherited properties should not count.

Comparisons

ApproachChecks own propertiesChecks inherited propertiesBest use
Object.hasOwn(obj, "key")YesNoRecommended modern own-property check
Object.prototype.hasOwnProperty.call(obj, "key")YesNoCompatibility-oriented safe check
obj.hasOwnProperty("key")UsuallyNoAvoid when data may be untrusted or unusual
"key" in objYesYesWhen inherited properties should count
obj.key !== undefinedNoCan be misleadingOnly when undefined is not a valid value

Existence versus value

const record = { value: undefined };

console.log(Object.hasOwn(record, "value")); // true
console.log(record.value !== undefined);      // false

The property exists, but its stored value is undefined. That is why property checks and value checks answer different questions.

Take Quiz

Cheat Sheet

// Recommended: direct/own property check
Object.hasOwn(object, "key");

// Safe alternative for older environments
Object.prototype.hasOwnProperty.call(object, "key");

// Includes own AND inherited properties
"key" in object;

Rules:

  • Prefer Object.hasOwn(obj, key) for plain data objects.
  • Do not use if (obj.key) to test whether a key exists.
  • false, 0, "", null, and undefined can all be stored values.
  • Use in only if prototype-chain properties should count.
  • Property names can be strings or symbols.
const obj = { active: false };

Object.hasOwn(obj, "active"); // true
obj.active;                     // false

FAQ

What is the best way to check if an object has a property in JavaScript?

Use Object.hasOwn(object, "propertyName") when you want to check whether the property is defined directly on the object.

Does hasOwnProperty() check inherited properties?

No. It checks only properties directly owned by the object. The in operator also checks inherited properties.

Why is Object.hasOwn() preferred over obj.hasOwnProperty()?

An object may not inherit hasOwnProperty, or it may contain a property with that same name. Object.hasOwn() avoids both problems.

Can I use if (object.key) to check whether a property exists?

Not reliably. It returns false for existing properties whose values are false, 0, "", null, or undefined.

What does the in operator do in JavaScript?

"key" in object returns true when the key exists directly on the object or anywhere in its prototype chain.

Does Object.hasOwn() work when the property value is undefined?

Yes. It checks whether the property exists, not the property's value.

Can property names be variables?

Yes. Pass the variable as the second argument.

const key = "email";
const user = { email: "ava@example.com" };

console.log(Object.hasOwn(user, key)); // true
Take Quiz

Mini Project

Description

Build a small settings updater that accepts a current settings object and a partial update object. It demonstrates why checking whether a key exists is different from checking whether its value is truthy.

Goal

Update only the settings explicitly present in an update object, including values such as false and 0.

Requirements

Requirement 1 Requirement 2 Requirement 3

Take Quiz

Keep learning

Related questions

View more