Own Properties in JavaScript

📌 What Are Own Properties?

In JavaScript, own properties are properties that belong directly to an object itself — not inherited through its prototype chain. These are the keys that the object explicitly has. 🧠

Note

Differentiating own properties from inherited ones is important when iterating over objects or manipulating data.

🔎 How to Identify Own Properties

You can check if a property is an own property of an object by using:

  • obj.hasOwnProperty(prop) — returns true if prop is an own property.
  • Object.hasOwn(obj, prop) — modern alternative (ES2022+).
  • Object.keys(obj) — returns an array of an object's own enumerable property names.

🧪 Examples

Checking Own Properties

const parent = { inheritedProp: "inherited" };
const child = Object.create(parent);
child.ownProp = "own";

console.log(child.hasOwnProperty("ownProp"));      // true
console.log(child.hasOwnProperty("inheritedProp")); // false

// Using Object.hasOwn (ES2022+)
console.log(Object.hasOwn(child, "ownProp"));       // true
console.log(Object.hasOwn(child, "inheritedProp")); // false

📋 Listing Own Properties

List Own Enumerable Properties

const obj = { a: 1, b: 2 };
console.log(Object.keys(obj)); // ["a", "b"]

Note that Object.keys() lists only own enumerable properties, not inherited or non-enumerable ones.

⚠️ Own vs Inherited Properties

When using for...in loops, both own and enumerable inherited properties are iterated:

for...in Loop Example

for (let key in child) {
  console.log(key);
}
// Outputs:
// ownProp
// inheritedProp

To filter only own properties, use hasOwnProperty() inside the loop:

Filtering Own Properties in for...in

for (let key in child) {
  if (child.hasOwnProperty(key)) {
    console.log(key); // only ownProp
  }
}

🧠 Why Own Properties Matter?

  • To avoid acting on inherited properties unintentionally
  • To ensure data encapsulation and object integrity
  • For accurate serialization or cloning

📚 Further Reading

>>“Own properties define the unique identity of an object; inherited ones add shared behavior.” 🔑