JavaScript Interview Question #123
What are property descriptors in JavaScript?
Closures, Prototypes, Classes & Advanced Functions Mid-Level Intermediate
Quick Interview Answer
Each ordinary object property has metadata describing characteristics such as value, writable, enumerable, and configurable. Accessor properties instead use get and set descriptors.
Detailed Explanation
Each ordinary object property has metadata describing characteristics such as value, writable, enumerable, and configurable. Accessor properties instead use get and set descriptors.
Object.getOwnPropertyDescriptor reads this metadata, while Object.defineProperty can define or modify a property with explicit descriptor settings. This provides finer control than ordinary assignment.
Code Example
const user = {};
Object.defineProperty(user, "id", {
value: 100,
writable: false,
enumerable: true,
configurable: false
});
console.log(
Object.getOwnPropertyDescriptor(user, "id")
);