Curriculum
Concept 52 // Module 06: Objects & Prototypal Inheritance
Property Accessors: Getters & Setters
Module 06: Objects & Prototypal Inheritance•Concept 52 of 100• 5 min read
Property Accessors: Getters & Setters
**Property Descriptors** (or Attributes) are the internal configurations of an object's properties. They define whether a property can be changed, deleted, or enumerated. Using `Object.defineProperty()`, you can control the 'physics' of an object.
The Core Concept
Syntax Reference
// 1. Getting Descriptors
Object.getOwnPropertyDescriptor(obj, 'prop');
// 2. Defining Descriptors
Object.defineProperty(obj, 'prop', {
value: 100,
writable: false, // Can value be changed?
enumerable: false, // Does it show up in loops?
configurable: false // Can descriptor be changed/deleted?
});
// 3. Getters/Setters (Accessor Descriptors)
Object.defineProperty(obj, 'name', {
get() { return this._name; },
set(v) { this._name = v; }
});
Live Interactive Studio
By setting `writable: false`, you create a property that cannot be changed. This is how internal JS constants are often implemented.
JavaScript Editor
Loading...
Console Output
Waiting for output...
Key Code Patterns in Action
01
Making a Constant Property
// 1. Making a Constant Property
const config = {};
Object.defineProperty(config, "API_KEY", {
value: "SECRET_123",
writable: false,
configurable: false
});
config.API_KEY = "HACKED"; // Silently fails (Error in strict mode)
console.log(config.API_KEY); // "SECRET_123"By setting `writable: false`, you create a property that cannot be changed. This is how internal JS constants are often implemented.
02
Hidden Properties (Enumerable)
// 2. Hidden Properties (Enumerable)
const user = { name: "Alex" };
Object.defineProperty(user, "internalId", {
value: 999,
enumerable: false // Hidden from loops
});
console.log(Object.keys(user)); // ["name"]
console.log(user.internalId); // 999 (Still accessible!)Non-enumerable properties are useful for metadata that you don't want to show up in JSON serialization or `for...in` loops.
03
Object Freezing
// 3. Object Freezing
const obj = { x: 10 };
Object.freeze(obj);
// Freezing sets all descriptors to writable: false
// and configurable: false for EVERY property.
obj.x = 20; // Fails`Object.freeze()` is a high-level utility that uses property descriptors under the hood to make an object immutable.
04
1. Core Usage: Property Accessors
// Core syntax and usage for Property Accessors: Getters & Setters
const feature = 'property-accessors-getters-setters';
console.log('Concept 52:', feature);
console.log('Active:', true);Illustrates the fundamental invocation and syntax structure for Property Accessors: Getters & Setters.
05
2. Defensive Handling & Edge Case
// Edge-case defensive handling
function handleSafe(input) {
if (input === null || input === undefined) return 'safe-fallback';
return String(input).trim();
}
console.log(handleSafe('property-accessors-getters-setters'));
console.log(handleSafe(null));Shows how to write defensive, safe JavaScript code that handles nullish or unexpected inputs when working with Property Accessors: Getters & Setters.
06
3. Clean Architecture & Production Pattern
// Production-grade pattern for Property Accessors: Getters & Setters
const settings = Object.freeze({
id: 'property-accessors-getters-setters',
ready: true,
timestamp: Date.now()
});
console.log('Settings initialized:', settings.id, settings.ready);Demonstrates clean, immutable production code avoiding unintended state mutations.
Real-World Engineering Takeaways
Library Development: Protecting internal state from user modification.
Frameworks: Implementing reactivity (Vue 2 uses getters/setters to track changes).
Legacy Interop: Emulating properties that behave like those in older JS versions.
Data Hardening: Creating secure configuration objects.
Under the Hood: Engine & Memory Mechanics
How JavaScript Executes This
### **Inside the Object**
**1. Descriptor Slots:**
- In the **Heap**, every object property isn't just a value.
- It's a structure containing the **Value** and a bitmask of **Flags** (W, E, C).
**2. Accessor Descriptors:**
- Getters and Setters are stored as **pointers** to function objects in the **Heap**.
- When you access the property, the **CPU** doesn't just read memory; it executes the pointed-to function.
**3. V8 Performance:**
- Frequently changing descriptors can break the engine's "Hidden Classes" optimization.
- **Rule:** Define your descriptors once at creation time for maximum performance in the **RAM**.
Quick Knowledge Check
Test your understanding on these 10 questions (one by one):
Score: 0 / 10
Question 1 of 10 • Core Purpose & Mental Model
What is the core purpose of Property Accessors: Getters & Setters in JavaScript?
// Concept 52: Property Accessors: Getters & Setters
// Understanding the core mental model1 / 10