JavaScript Property Descriptors, defineProperty and Reflect
Learn property descriptors: writable, enumerable, configurable, Object.defineProperty, accessor properties and the Reflect API, with clear real examples.
What you will learn
You have created hundreds of properties, like user.name = "Riya". But did you know that every property secretly carries a small set of settings? These settings decide whether the property can be changed, whether it shows up in loops, and whether it can be deleted. You already met their effects without knowing it: Object.freeze locks properties, for...in skips some of them, and class methods do not appear in Object.keys.
In this lesson you will learn to see these settings with property descriptors, to control them with Object.defineProperty(), to write getters and setters with it, and to use the Reflect API, a set of tidy functions for working with objects. This lesson also prepares you for the next topic, Proxy, which works hand in hand with Reflect.
The idea in one line
Every property is not just a value. It is a value plus three switches: writable, enumerable and configurable.
Think of a document file on a computer. A file has content, but also settings: read-only (can you edit it?), hidden (do you see it in the folder?), and locked (can you delete or rename it?). A property is like that file. The descriptor is its settings sheet.
Seeing a descriptor
Use Object.getOwnPropertyDescriptor(object, "key"):
const user = { name: "Riya", city: "Delhi" };
console.log(Object.getOwnPropertyDescriptor(user, "name"));
// { value: "Riya", writable: true, enumerable: true, configurable: true }
A normal property, created by assignment or an object literal, has all three switches on. The result is the descriptor, a small object with four parts for a data property:
| Part | Meaning |
|---|---|
value |
The actual value |
writable |
Can the value be changed? |
enumerable |
Does it show up in Object.keys, for...in, JSON.stringify and spread? |
configurable |
Can it be deleted, or its settings changed? |
Some built-in properties have switches turned off:
console.log(Object.getOwnPropertyDescriptor(Math, "PI"));
// { value: 3.141592653589793, writable: false, enumerable: false, configurable: false }
console.log(Object.getOwnPropertyDescriptor([10, 20], "length"));
// { value: 2, writable: true, enumerable: false, configurable: false }
That is why Math.PI = 3 does nothing (it is not writable), and why length never shows in Object.keys(array) (it is not enumerable).
To see all descriptors of an object at once, use Object.getOwnPropertyDescriptors(object) (with an s):
const point = { x: 1, y: 2 };
console.log(Object.getOwnPropertyDescriptors(point));
// {
// x: { value: 1, writable: true, enumerable: true, configurable: true },
// y: { value: 2, writable: true, enumerable: true, configurable: true }
// }
Creating properties with Object.defineProperty()
Object.defineProperty(object, "key", descriptor) adds (or changes) a property and lets you choose the switches.
const user = { name: "Riya" };
Object.defineProperty(user, "id", {
value: 101,
writable: false,
enumerable: false,
configurable: false
});
console.log(user.id); // 101
The big gotcha: the switches default to false
When you create a property with assignment, all switches are true. When you create it with defineProperty, every switch you do not write is false:
const a = {};
a.score = 10; // assignment: all true
const b = {};
Object.defineProperty(b, "score", { value: 10 }); // defineProperty: all false
console.log(Object.getOwnPropertyDescriptor(a, "score"));
// { value: 10, writable: true, enumerable: true, configurable: true }
console.log(Object.getOwnPropertyDescriptor(b, "score"));
// { value: 10, writable: false, enumerable: false, configurable: false }
So b.score is read-only, hidden from loops, and cannot be deleted, just from forgetting to write the switches. Always write the ones you care about.
Changing an existing property
If the property already exists, only the settings you write are changed. The others stay as they were.
const user = { name: "Riya" };
Object.defineProperty(user, "name", { writable: false }); // only this switch changes
console.log(Object.getOwnPropertyDescriptor(user, "name"));
// { value: "Riya", writable: false, enumerable: true, configurable: true }
Many at once: Object.defineProperties()
const product = {};
Object.defineProperties(product, {
title: { value: "Pen", enumerable: true },
price: { value: 20, enumerable: true, writable: true }
});
The three switches, one by one
1. writable: can the value change?
"use strict";
const settings = {};
Object.defineProperty(settings, "version", {
value: "1.0",
writable: false,
enumerable: true
});
settings.version = "2.0"; // TypeError in strict mode (silently ignored in normal mode)
console.log(settings.version); // "1.0"
This matches what you learned in the strict mode lesson: breaking a rule fails silently in normal mode, and throws a TypeError in strict mode. Classes and modules are always strict.
2. enumerable: does it show in loops?
A non-enumerable property exists and works, but it is hidden from the usual list-making tools:
const user = { name: "Riya", city: "Delhi" };
Object.defineProperty(user, "secretId", {
value: "A-123",
enumerable: false,
writable: true,
configurable: true
});
console.log(user.secretId); // "A-123" (it works)
console.log(Object.keys(user)); // ["name", "city"]
console.log(Object.entries(user)); // [["name","Riya"],["city","Delhi"]]
console.log(JSON.stringify(user)); // {"name":"Riya","city":"Delhi"}
console.log({ ...user }); // { name: "Riya", city: "Delhi" }
console.log(Object.assign({}, user)); // { name: "Riya", city: "Delhi" }
for (const key in user) {
console.log(key); // "name", then "city" (no secretId)
}
A few tools can still see it:
console.log(Object.getOwnPropertyNames(user)); // ["name", "city", "secretId"]
console.log(user.propertyIsEnumerable("secretId")); // false
console.log("secretId" in user); // true
console.log(Object.hasOwn(user, "secretId")); // true
This is exactly how the class methods from the classes lesson stay out of for...in:
class Person {
greet() {
return "Hi";
}
}
console.log(Object.getOwnPropertyDescriptor(Person.prototype, "greet"));
// { value: [Function: greet], writable: true, enumerable: false, configurable: true }
Methods written with class are created with enumerable: false. (Methods that you add by plain assignment, like Person.prototype.greet = function () {}, are enumerable, as the constructor functions lesson showed.)
3. configurable: can it be deleted or redefined?
When configurable is false:
- you cannot delete the property,
- you cannot change
enumerableorconfigurable, or turn it into a getter/setter, - (an exception:
writablecan still go fromtruetofalse, but never back totrue).
"use strict";
const config = {};
Object.defineProperty(config, "apiUrl", {
value: "https://api.example.com",
enumerable: true
}); // configurable is false (the default)
try {
delete config.apiUrl;
} catch (error) {
console.log(error.name); // "TypeError"
}
try {
Object.defineProperty(config, "apiUrl", { value: "https://other.com" });
} catch (error) {
console.log(error.message); // "Cannot redefine property: apiUrl"
}
Setting configurable: false is a one-way door. You cannot undo it. Use it when a property must stay forever.
Summary table
| Switch | When false… |
Default with defineProperty |
|---|---|---|
writable |
Assignment does not change the value | false |
enumerable |
Hidden from Object.keys, for...in, JSON.stringify, spread |
false |
configurable |
Cannot delete or redefine the property | false |
How Object.freeze and Object.seal really work
In the Object methods lesson you learned Object.freeze and Object.seal as locks. Now you can see what they do inside.
const frozen = Object.freeze({ a: 1 });
console.log(Object.getOwnPropertyDescriptor(frozen, "a"));
// { value: 1, writable: false, enumerable: true, configurable: false }
Object.freezesets every property towritable: falseandconfigurable: false, and stops new properties from being added.Object.sealsets every property toconfigurable: false(values can still change), and stops new properties.
| Add new | Delete | Change value | |
|---|---|---|---|
| Normal object | Yes | Yes | Yes |
seal |
No | No | Yes |
freeze |
No | No | No |
And remember what the lesson told you: freeze is shallow. It only changes the descriptors of the top-level properties, so objects inside stay changeable. You can fix that with a deepFreeze function, which you will build below.
Accessor properties: getters and setters with defineProperty
So far, the property had a value. There is a second kind: an accessor property, which has get and set functions instead. You know it as the get name() {} and set name(v) {} syntax from the classes lesson. defineProperty is the long form of the same thing.
const person = { firstName: "Riya", lastName: "Sharma" };
Object.defineProperty(person, "fullName", {
get() {
return this.firstName + " " + this.lastName;
},
set(value) {
const parts = value.split(" ");
this.firstName = parts[0];
this.lastName = parts[1];
},
enumerable: true,
configurable: true
});
console.log(person.fullName); // "Riya Sharma"
person.fullName = "Karan Mehta";
console.log(person.firstName); // "Karan"
Here the descriptor has get and set instead of value and writable:
| Data property | Accessor property |
|---|---|
value |
get |
writable |
set |
enumerable |
enumerable |
configurable |
configurable |
You cannot mix them. A descriptor with value or writable and get or set throws a TypeError:
try {
Object.defineProperty({}, "x", { value: 1, get() { return 1; } });
} catch (error) {
console.log(error.name); // "TypeError"
}
A getter and setter that guard a value
function createUser(name, startAge) {
const user = { name };
let age = startAge; // private: hidden in the closure
Object.defineProperty(user, "age", {
get() {
return age;
},
set(value) {
if (typeof value !== "number" || value < 0 || value > 120) {
throw new RangeError("Age must be from 0 to 120");
}
age = value;
},
enumerable: true
});
return user;
}
const riya = createUser("Riya", 20);
riya.age = 21;
console.log(riya.age); // 21
console.log(JSON.stringify(riya)); // {"name":"Riya","age":21}
try {
riya.age = -5;
} catch (error) {
console.log(error.message); // "Age must be from 0 to 120"
}
The real value lives in a closure variable, so there is no _age property for others to touch (this is the better version of the underscore habit, from the closures lesson).
Getters on the prototype and this
A getter is a normal function, so this follows the usual rules from the this keyword lesson: it is the object before the dot. This is why a getter on a prototype can serve many objects.
const base = {
get describe() {
return this.name + " is " + this.age;
}
};
const riya = Object.create(base);
riya.name = "Riya";
riya.age = 21;
console.log(riya.describe); // "Riya is 21" (this is riya)
Copying objects that have getters
Object.assign and the spread operator read every value, and they copy only the result of a getter. The getter itself is lost:
const source = {
first: "Riya",
get shout() {
return this.first.toUpperCase() + "!";
}
};
const copy = { ...source };
console.log(Object.getOwnPropertyDescriptor(copy, "shout"));
// { value: "RIYA!", writable: true, enumerable: true, configurable: true } (a frozen snapshot)
copy.first = "Karan";
console.log(copy.shout); // "RIYA!" (it did not update)
To copy the full descriptors, including getters and setters, combine getOwnPropertyDescriptors with defineProperties:
const clone = Object.defineProperties({}, Object.getOwnPropertyDescriptors(source));
clone.first = "Karan";
console.log(clone.shout); // "KARAN!" (the getter was copied, so it still works)
You can also copy the prototype at the same time:
const fullClone = Object.create(
Object.getPrototypeOf(source),
Object.getOwnPropertyDescriptors(source)
);
(Object.create accepts descriptors as its second argument.)
Reflect: tidy functions for object operations
You already use operators to work with objects: in, delete, new, and the dot. Reflect is a built-in object that offers the same operations as plain functions, with more consistent behaviour. It is not a constructor, so you never write new Reflect(). You just call its methods.
Why does Reflect exist?
- One home for object operations. Instead of a mix of operators (
in,delete) and functions (Object.keys), you get a clean, matching set. - Returns
trueorfalseinstead of throwing errors (for exampleReflect.definePropertyreturnsfalsewhereObject.definePropertythrows). - Works with the
receiver, which controlsthisinside getters (an advanced detail you will meet with Proxy). - It matches every trap of Proxy, so a Proxy can easily “do the normal thing” (the next lesson).
The Reflect methods
Reflect method |
Same as | Returns |
|---|---|---|
Reflect.get(obj, key) |
obj[key] |
The value |
Reflect.set(obj, key, value) |
obj[key] = value |
true or false |
Reflect.has(obj, key) |
key in obj |
true or false |
Reflect.deleteProperty(obj, key) |
delete obj[key] |
true or false |
Reflect.ownKeys(obj) |
all own keys | Array of strings and symbols |
Reflect.defineProperty(obj, key, desc) |
Object.defineProperty |
true or false (no throw) |
Reflect.getOwnPropertyDescriptor(obj, key) |
Object.getOwnPropertyDescriptor |
The descriptor |
Reflect.getPrototypeOf(obj) |
Object.getPrototypeOf |
The prototype |
Reflect.setPrototypeOf(obj, proto) |
Object.setPrototypeOf |
true or false |
Reflect.isExtensible(obj) |
Object.isExtensible |
true or false |
Reflect.preventExtensions(obj) |
Object.preventExtensions |
true or false |
Reflect.apply(fn, thisArg, args) |
fn.apply(thisArg, args) |
The result of the function |
Reflect.construct(Class, args) |
new Class(...args) |
The new object |
Reflect.get, Reflect.set, Reflect.has
const user = { name: "Riya" };
console.log(Reflect.get(user, "name")); // "Riya"
console.log(Reflect.set(user, "age", 21)); // true (and user.age is now 21)
console.log(Reflect.has(user, "age")); // true
console.log(Reflect.has(user, "toString")); // true (like "in", it checks the chain)
Success or failure, without try/catch
The big practical difference: the write operations return a boolean instead of failing quietly or throwing.
const config = Object.freeze({ mode: "dark" });
console.log(Reflect.set(config, "mode", "light")); // false (frozen, no error even in strict mode)
console.log(Reflect.deleteProperty(config, "mode")); // false
console.log(Reflect.defineProperty(config, "x", { value: 1 })); // false
"use strict"; // (a normal assignment would throw a TypeError in strict mode)
With plain operators you would need strict mode and a try/catch. With Reflect you just check the answer:
if (!Reflect.set(config, "mode", "light")) {
console.log("Could not change the setting");
}
Reflect.ownKeys: truly all the keys
Object.keys returns only own, enumerable, string keys. Reflect.ownKeys returns every own key: strings, symbols (from the Symbols lesson), and non-enumerable ones.
const id = Symbol("id");
const user = { name: "Riya", [id]: 1 };
Object.defineProperty(user, "hidden", { value: "x", enumerable: false });
console.log(Object.keys(user)); // ["name"]
console.log(Reflect.ownKeys(user)); // ["name", "hidden", Symbol(id)]
Reflect.apply: the safe apply
You learned fn.apply(thisArg, args) in the call, apply and bind lesson. A function can have its own apply property by mistake, and then fn.apply breaks. Reflect.apply always works the same way:
console.log(Reflect.apply(Math.max, null, [4, 9, 2])); // 9
console.log(Reflect.apply(String.prototype.toUpperCase, "hello", [])); // "HELLO"
Reflect.construct: new as a function
new is a keyword, so you cannot easily call it with a dynamic class or an array of arguments. Reflect.construct does the four steps of new from the constructor functions lesson as a normal function:
class Product {
constructor(title, price) {
this.title = title;
this.price = price;
}
}
const args = ["Pen", 20];
const pen = Reflect.construct(Product, args); // same as new Product(...args)
console.log(pen); // Product { title: "Pen", price: 20 }
console.log(pen instanceof Product); // true
It has an optional third argument, newTarget, which decides which prototype the new object gets:
class Animal {
constructor(name) {
this.name = name;
}
}
class Dog extends Animal {}
const strange = Reflect.construct(Animal, ["Bruno"], Dog);
console.log(strange instanceof Dog); // true (built by Animal, but linked to Dog)
The receiver: what this is inside a getter
Reflect.get and Reflect.set take an optional receiver, the object to use as this inside a getter or setter:
const person = {
first: "Riya",
last: "Sharma",
get full() {
return this.first + " " + this.last;
}
};
const other = { first: "Karan", last: "Mehta" };
console.log(Reflect.get(person, "full")); // "Riya Sharma"
console.log(Reflect.get(person, "full", other)); // "Karan Mehta" (this is other)
It is like the thisArg of call. For everyday code you will rarely need it, but it is the key to writing correct Proxies, which is why you are learning it now.
Real-life use cases
1. Read-only constants (a safe config)
const config = {};
Object.defineProperties(config, {
API_URL: { value: "https://api.example.com", enumerable: true },
MAX_RETRIES: { value: 3, enumerable: true }
});
config.MAX_RETRIES = 99; // ignored (or TypeError in strict mode)
console.log(config.MAX_RETRIES); // 3
console.log(Object.keys(config)); // ["API_URL", "MAX_RETRIES"]
2. A hidden property that stays out of JSON and loops
function createRecord(data) {
const record = { ...data };
Object.defineProperty(record, "_internalId", {
value: Math.random().toString(36).slice(2, 8),
enumerable: false // hidden
});
return record;
}
const record = createRecord({ title: "Report", pages: 12 });
console.log(JSON.stringify(record)); // {"title":"Report","pages":12} (no internal id)
console.log(record._internalId.length); // 6 (still available in code)
Useful for metadata that must never be sent to a server or shown to the user.
3. A validated property (with a WeakMap as the private store)
The WeakMap lesson showed WeakMap as a way to keep private data. You can combine it with accessors:
const privateAge = new WeakMap();
function makeStudent(name, age) {
const student = { name };
privateAge.set(student, age);
Object.defineProperty(student, "age", {
get() {
return privateAge.get(this);
},
set(value) {
if (value < 5 || value > 100) throw new RangeError("Invalid age");
privateAge.set(this, value);
},
enumerable: true
});
return student;
}
const riya = makeStudent("Riya", 15);
riya.age = 16;
console.log(riya.age); // 16
4. A lazy, cached property
Calculate an expensive value only the first time it is read, then replace the getter with the plain value:
const report = {
get data() {
console.log("Calculating... (this prints only once)");
const result = [1, 2, 3, 4, 5].map((n) => n * n);
Object.defineProperty(this, "data", {
value: result,
enumerable: true
});
return result;
}
};
console.log(report.data); // "Calculating..." then [1, 4, 9, 16, 25]
console.log(report.data); // [1, 4, 9, 16, 25] (no calculation this time)
After the first read, data is a normal read-only value, so the work is never repeated.
5. A real deepFreeze
Object.freeze is shallow. This function freezes everything inside, using Reflect.ownKeys so no key (even a symbol) is missed:
function deepFreeze(object) {
Reflect.ownKeys(object).forEach((key) => {
const value = object[key];
if (value && typeof value === "object" && !Object.isFrozen(value)) {
deepFreeze(value);
}
});
return Object.freeze(object);
}
const settings = deepFreeze({
theme: "dark",
server: { host: "localhost", ports: [3000, 3001] }
});
"use strict";
// settings.server.host = "x"; // fails: frozen (TypeError in strict mode)
// settings.server.ports.push(3002); // TypeError: the array is frozen too
console.log(Object.isFrozen(settings.server.ports)); // true
6. A debug helper: list properties with their settings
function inspect(object) {
return Reflect.ownKeys(object).map((key) => {
const d = Reflect.getOwnPropertyDescriptor(object, key);
const kind = "value" in d ? "data" : "accessor";
return String(key) + " [" + kind + "]" +
" writable=" + Boolean(d.writable) +
" enumerable=" + d.enumerable +
" configurable=" + d.configurable;
});
}
console.log(inspect({ a: 1, get b() { return 2; } }));
// ["a [data] writable=true enumerable=true configurable=true",
// "b [accessor] writable=false enumerable=true configurable=true"]
7. Safe updates that report success
function trySet(object, key, value) {
const ok = Reflect.set(object, key, value);
if (!ok) {
console.warn("Could not set " + String(key));
}
return ok;
}
const locked = Object.freeze({ plan: "free" });
trySet(locked, "plan", "pro"); // warning, and no crash
Where this knowledge helps in daily work
- Reading library code. Libraries often use
definePropertyto hide internals andReflectfor safe operations. - Understanding errors like “Cannot assign to read only property” or “Cannot redefine property”. Now you know the switch behind them.
- Debugging why a property is missing from
JSON.stringifyorObject.keys(it may be non-enumerable). - Writing Proxies (next lesson), where
Reflectis the standard partner.
You will not write defineProperty every day. Most of the time a class with private fields or a plain Object.freeze is enough. But you now understand how it all works.
Common mistakes
- Forgetting that
definePropertyswitches default tofalse. The property ends up read-only, hidden and permanent. Write the switches you need. - Mixing
valueorwritablewithgetorset. It throws aTypeError. Choose one kind. - Using
this.ageinside theagegetter or setter. It calls itself forever. Store the real value in a closure variable or a WeakMap. - Expecting
enumerable: falseto be private. The property is only hidden from lists.object.secretIdstill works, andObject.getOwnPropertyNamesstill sees it. For real privacy, use#private fields. - Setting
configurable: falseand then trying to change it. It is a one-way door. - Expecting spread or
Object.assignto copy getters. They copy the result. UsegetOwnPropertyDescriptorswithdefineProperties. - Expecting
Object.freezeto freeze nested objects. It is shallow. Use adeepFreezefunction. - Using
Object.keysto find all keys, and missing symbols and non-enumerable keys. UseReflect.ownKeys. - Forgetting that
Reflect.setandReflect.deletePropertyreturnfalseon failure instead of throwing. Check the result. - Writing
new Reflect().Reflectis not a class. Call its methods directly. - Passing a wrong argument type.
Reflectmethods need an object as the target, and throw aTypeErrorfor a primitive (Reflect.get(5, "x")).
Practice
- Create
const user = { name: "Riya" }and printObject.getOwnPropertyDescriptor(user, "name"). Explain each of the four parts. - Print the descriptors of
Math.PIand of[1, 2, 3].length. Which switches arefalse, and what does that mean? - Add
idwithObject.defineProperty(user, "id", { value: 1 })and print its descriptor. Why are all the switchesfalse? - Try to change
user.id, delete it, and printObject.keys(user). Do it again with"use strict"at the top and compare. - Make a property
secretCodewithenumerable: false(andwritable: true). CheckObject.keys,JSON.stringify,for...in,Object.getOwnPropertyNamesand"secretCode" in user. - Make a property with
configurable: false, then try to delete it and to redefine it. Read the error messages. - Prove that
writablecan go fromtruetofalseon a non-configurable property, but not back. - Freeze an object and print the descriptor of one of its properties. Do the same after
Object.sealand compare. - Print the descriptor of a class method (
Class.prototype.method). Why isenumerablefalse? - Write
fullNameas a getter and setter usingObject.defineProperty. Make the setter split a string intofirstNameandlastName. - Try to define a property with both
valueandget. Read the error. - Create an object with a getter and copy it with the spread operator. Print the descriptor of the copy, and explain what was lost. Then copy it correctly with
getOwnPropertyDescriptors. - Make a
createUser(name, age)function with a validatedageaccessor that stores the value in a closure. Try to set-5. - Compare
Object.keys(obj)andReflect.ownKeys(obj)on an object with a symbol key and a non-enumerable key. - Use
Reflect.setandReflect.deletePropertyon a frozen object and print the results. Then useReflect.definePropertyand compare withObject.defineProperty(which throws). - Use
Reflect.apply(Math.min, null, array)andReflect.construct(Date, [2026, 0, 1]). - Use
Reflect.get(person, "full", other)with a getter that readsthis, and explain which objectthisis. - Challenge: write
deepFreeze(object)from memory. Test it on a nested object with an array. - Challenge: write a lazy property that calculates a value on the first read, then replaces itself with the plain value. Prove that the calculation runs only once.
- Challenge: write
makeReadOnly(object)that returns a copy of the object (with descriptors, including getters) where every property iswritable: falseandconfigurable: false, but the object can still get new properties. - Challenge: write
inspect(object)that prints every key (including symbols) with its kind (data or accessor) and its three switches.
Recap
- Every property has a descriptor. A data property has
value,writable,enumerableandconfigurable. An accessor property hasget,set,enumerableandconfigurable. You cannot mix the two kinds. Object.getOwnPropertyDescriptor(and the pluralgetOwnPropertyDescriptors) shows the settings. Properties created by assignment have all switchestrue.Object.defineProperty(obj, key, descriptor)creates or changes a property. For new properties, every switch you leave out isfalse. For existing properties, only the switches you write change.writable: falseblocks value changes.enumerable: falsehides a property fromObject.keys,for...in,JSON.stringifyand spread (but not fromgetOwnPropertyNames).configurable: falseblocks delete and redefine, and it is a one-way door.Object.freezeandObject.sealsimply turn these switches off for all properties. Freeze is shallow.- Class methods are non-enumerable, which is why they do not appear in
for...in. - Spread and
Object.assigncopy only values. To copy getters and setters too, useObject.defineProperties({}, Object.getOwnPropertyDescriptors(source)). Reflectgives the operations of the language as functions:get,set,has,deleteProperty,ownKeys,defineProperty,apply,constructand more. Write operations returntrueorfalseinstead of throwing, andReflect.ownKeysfinds every key, including symbols and hidden ones.Reflect.applyis a safefn.apply, andReflect.constructisnewas a function (withnewTarget). The optional receiver setsthisinside getters.- Next you will learn Proxy: objects that can intercept reading, writing, deleting and more.
Reflectis its perfect partner.
If you want to revisit the basics, read the Object methods lesson, the classes lesson, the Symbols lesson and the strict mode lesson.
Frequently asked questions
What is a property descriptor in JavaScript?
It is an object that describes a property’s settings. For a normal data property it has value, writable, enumerable and configurable. You read it with Object.getOwnPropertyDescriptor() and set it with Object.defineProperty().
What do writable, enumerable and configurable mean?
writable says whether the value can be changed. enumerable says whether the property appears in loops, Object.keys, JSON.stringify and spread. configurable says whether the property can be deleted or have its settings changed.
Why is my property missing from Object.keys or JSON.stringify?
It is probably non-enumerable. Properties created with Object.defineProperty default to enumerable: false. Check it with Object.getOwnPropertyDescriptor(obj, “key”), and add enumerable: true if it should be visible.
What is the difference between a data property and an accessor property?
A data property stores a value. An accessor property has a getter and/or setter function that runs when you read or write it. A single property is one or the other, never both at the same time.
What is the Reflect object used for?
Reflect provides the basic object operations (get, set, has, delete, define, apply, construct and more) as functions with consistent return values. Write operations return true or false instead of throwing. It is most useful together with Proxy.
Is a non-enumerable property private?
No. It is only hidden from the usual lists. You can still read it by name, and tools like Object.getOwnPropertyNames and Reflect.ownKeys show it. For real privacy, use private fields with #.
See also: Object Methods, Classes, Call, Apply and Bind, JavaScript Cheat Sheet