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?”
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:
trueifpropertyNameis directly defined onobjectfalseotherwise
Reading a property is not the same as checking for it
const settings = {
darkMode: false
};
console.log(settings.);
.(.(settings, ));
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:
profileis created with two own properties:usernameandsubscribed.Object.hasOwn(profile, "subscribed")checks the properties directly stored onprofile.- It finds
subscribed, so it returnstrue. hasSubscribedPropertyreceivestrue.- The
ifcondition 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
emailbefore deciding whether to update it. - Partial updates: Distinguish “the user set
enabledtofalse” from “the user did not sendenabled.” - 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.(settings.);
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 .
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
Comparisons
| Approach | Checks own properties | Checks inherited properties | Best use |
|---|---|---|---|
Object.hasOwn(obj, "key") | Yes | No | Recommended modern own-property check |
Object.prototype.hasOwnProperty.call(obj, "key") | Yes | No | Compatibility-oriented safe check |
obj.hasOwnProperty("key") | Usually | No | Avoid when data may be untrusted or unusual |
"key" in obj | Yes | Yes | When inherited properties should count |
obj.key !== undefined | No |
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, andundefinedcan all be stored values.- Use
inonly if prototype-chain properties should count. - Property names can be strings or symbols.
const obj = { active: false };
Object.hasOwn(obj, "active");
obj.;
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 when the key exists directly on the object or anywhere in its prototype chain.
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
Keep learning
Related questions
Abort Ajax Requests with jQuery jqXHR.abort()
Learn how to cancel an in-progress jQuery Ajax request with jqXHR.abort(), handle abort status safely, and avoid stale UI updates.
Access the Correct this Inside a JavaScript Callback
Learn why JavaScript this changes in callbacks and how to preserve an object context using bind, arrow functions, and event handler patterns.
Add Key-Value Pairs to JavaScript Objects
Learn how to add key-value pairs to JavaScript objects with dot and bracket notation, dynamic keys, examples, and common mistakes.