Ankaj Gupta
August 18, 2020

JavaScript check property exists

JavaScript Reference

Check if a JavaScript Object Has a Property

Objects in JavaScript are flexible—you can add or remove properties at runtime. To write defensive code, confirm a property exists before using it. This guide compares the in operator and hasOwnProperty() method.

What You’ll Learn

  • How the in operator works
  • When to prefer hasOwnProperty()
  • Pros and cons of each approach

Reminder: Prototype chains mean an object may inherit properties you didn’t add explicitly. These checks help avoid unexpected behavior.

Using the in Operator

The expression 'property' in object returns true if the property exists either directly on the object or somewhere along its prototype chain.

const book = { title: "JavaScript" };

console.log('title' in book); // true
console.log('id' in book);    // false
console.log('toString' in book); // true (comes from Object.prototype)

Using hasOwnProperty()

The hasOwnProperty() method checks only the object’s own properties, ignoring inherited ones.

console.log(book.hasOwnProperty('title'));    // true
console.log(book.hasOwnProperty('id'));       // false
console.log(book.hasOwnProperty('toString')); // false (inherited)

Comparing in vs hasOwnProperty()

Scenario Use Reason
Need to check prototype chain too 'property' in object Covers inherited properties
Verify only custom/own keys object.hasOwnProperty('property') Ignores prototype pollution

Putting It Together

const article = Object.create({ slug: 'shared-slug' });
article.title = 'Understanding Property Checks';

console.log('title' in article);          // true
console.log(article.hasOwnProperty('title')); // true

console.log('slug' in article);              // true (inherited)
console.log(article.hasOwnProperty('slug')); // false

Recommendation: Use hasOwnProperty() to guard user-controlled data, and fall back to in when prototype values should count.

Reusable Utility Helper

export function hasOwn(object, key) {
    return Object.prototype.hasOwnProperty.call(object, key);
}

// Example usage
const config = { theme: 'dark' };
console.log(hasOwn(config, 'theme'));   // true
console.log(hasOwn(config, 'layout')); // false

Key Takeaways

  • The in operator returns true for own and inherited properties.
  • hasOwnProperty() checks only own properties, guarding against prototype pollution.
  • Wrap property checks in utility helpers to centralize edge-case handling across your codebase.
JavaScript

Join the discussion

Comments

0 comments

No comments yet — be the first to share your thoughts.

Related Posts