Enumerable Properties in JavaScript
📌 What Are Enumerable Properties?
In JavaScript, enumerable properties are object properties that can be iterated over — for example, by a for...in loop or Object.keys(). These properties are marked with the enumerable attribute set to true. 🔍
🧩 Property Attributes
Every object property has special internal attributes, also called property descriptors:
- value: The property's value
- writable: If the property's value can be changed
- configurable: If the property can be deleted or changed
- enumerable: If the property shows up during enumeration (e.g., in for...in loops)
🧪 Checking Enumerable Properties
Example: Check Enumerable Property
const obj = { name: "Alice" };
// Default enumerable is true
console.log(obj.propertyIsEnumerable("name")); // true⚙️ Defining Enumerable Properties
You can define or modify the enumerable attribute using Object.defineProperty():
Making a Property Non-Enumerable
const obj = { name: "Alice" };
Object.defineProperty(obj, "secret", {
value: "hidden",
enumerable: false
});
console.log(Object.keys(obj)); // ["name"]
console.log(obj.secret); // "hidden"The secret property does not show up during enumeration because it is non-enumerable.
🔎 Enumerating Enumerable Properties
Enumerable properties are included in:
- for...in loops
- Object.keys()
- JSON.stringify() (only enumerable own properties)
⚠️ Non-Enumerable Properties
Non-enumerable properties are usually internal or built-in methods to keep them hidden from enumeration. For example, many built-in methods like toString() are non-enumerable.
Example: Non-enumerable Built-in Properties
console.log(Object.keys({}.toString)); // []
console.log({}.propertyIsEnumerable("toString")); // false🧠 Why Use Non-Enumerable Properties?
- To hide implementation details from loops or JSON output
- To prevent accidental modification or enumeration of sensitive data
📚 Summary
- Enumerable properties appear during property enumeration
- The enumerable attribute controls this behavior
- You can customize enumerability using Object.defineProperty()
- Most user-defined properties are enumerable by default
📖 References
>>“Controlling property enumerability helps you manage what your objects reveal to the outside world.” 🔐