Skip to content
jshacks.dev
Fundamentals

JavaScript Object.defineProperty Explained With Examples

Object.defineProperty() sets a property and its attributes: writable, enumerable, configurable, getters and setters. See the defaults that catch people out.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, TypeScript, Node.js, npm and Vite logos.

You define a property with Object.defineProperty(obj, "id", { value: 7 }), assign a new value later, and nothing happens. No error, no change. Then you check Object.keys(obj) and the property is missing from that too. Both effects come from the same rule: when you define a property this way, every attribute you do not mention defaults to false, which is the opposite of what an ordinary assignment gives you. This post explains the three attributes, the accessor form, what redefinition allows and forbids, and the places where Object.freeze() or a class field is the simpler answer. It is the single-property sibling of [the post on Object.create()](/library/javascript-object-create), which takes the same descriptors in bulk. Everything here runs on Node.js 24.

What defineProperty() takes and returns

The signature is Object.defineProperty(obj, key, descriptor). It creates the property if it does not exist, or changes it if it does, and returns the same object you passed in. The key can be a string or a symbol.

Descriptor fieldApplies toDefault when creating
valueData propertyundefined
writableData propertyfalse
getAccessor propertyundefined
setAccessor propertyundefined
enumerableBothfalse
configurableBothfalse

A property is either a data property or an accessor property, never both. The method has been in the language since ES5.

JavaScript
const user = {};
const returned = Object.defineProperty(user, "id", { value: 7 });

console.log(returned === user);
console.log(Object.getOwnPropertyDescriptor(user, "id"));
console.log(Object.keys(user));
console.log(user.id);
Text
true
{ value: 7, writable: false, enumerable: false, configurable: false }
[]
7

The property exists and holds 7, but it is read-only, invisible to Object.keys(), and cannot be deleted or reconfigured. Compare that with the same property created by assignment.

JavaScript
const user = {};
user.id = 7;

console.log(Object.getOwnPropertyDescriptor(user, "id"));
Text
{ value: 7, writable: true, enumerable: true, configurable: true }

Assignment defaults every attribute to true. The difference between those two descriptors is the whole subject of this post.

The three attributes in practice

writable controls whether the value can be replaced. A failed write is silent in sloppy mode and throws in strict mode. Classes and modules are always strict, and a function can opt in with a directive.

JavaScript
const config = {};
Object.defineProperty(config, "mode", { value: "prod", enumerable: true });

config.mode = "dev";
console.log(config.mode);

function strictWrite() {
  "use strict";
  config.mode = "dev";
}

try {
  strictWrite();
} catch (err) {
  console.log(err.name);
  console.log(err.message);
}
Text
prod
TypeError
Cannot assign to read only property 'mode' of object '#<Object>'

The first write was ignored without a sound. The strict one threw. That asymmetry is why bugs around read-only properties hide so well in older sloppy code.

enumerable controls visibility to iteration. for...in, Object.keys(), Object.entries(), spread and JSON.stringify() all skip non-enumerable properties, and so does the default console.log() output.

JavaScript
const record = { visible: 1 };
Object.defineProperty(record, "hidden", { value: 2 });

console.log(record);
console.log(JSON.stringify(record));
console.log(Object.getOwnPropertyNames(record));
console.log(record.hidden);
Text
{ visible: 1 }
{"visible":1}
[ 'visible', 'hidden' ]
2

hidden is still readable and still an own property. Object.getOwnPropertyNames() lists it, which is the usual way to find properties that the enumerable-only methods skip. See [the post on Object.getOwnPropertyNames()](/library/javascript-object-getownpropertynames) for that.

configurable controls whether the property can be deleted and whether its attributes can change again. It is the one-way door of the three.

Redefining and the one-way door

Calling defineProperty() on an existing property only changes the fields you pass. Everything else keeps its current value.

JavaScript
const o = { a: 1 };
Object.defineProperty(o, "a", { enumerable: false });

console.log(Object.getOwnPropertyDescriptor(o, "a"));
Text
{ value: 1, writable: true, enumerable: false, configurable: true }

The value stayed, and only enumerable flipped. That is the defaults rule applied only on creation. Once a property is non-configurable, most changes are refused with a TypeError. A few remain allowed: a writable data property can still have its value changed, and its writable can go from true to false, but never back.

JavaScript
const o = {};
Object.defineProperty(o, "x", { value: 1, writable: true });

Object.defineProperty(o, "x", { value: 2 });
Object.defineProperty(o, "x", { writable: false });
console.log(o.x);

try {
  Object.defineProperty(o, "x", { value: 3 });
} catch (err) {
  console.log(err.name, err.message);
}

console.log(delete o.x);
console.log("x" in o);
Text
2
TypeError Cannot redefine property: x
false
true

The last two lines show the delete. In sloppy mode delete on a non-configurable property returns false and does nothing, so "x" in o is still true. In strict mode, that delete would throw a TypeError instead.

Accessor properties

Instead of a value, you can supply get and set functions. The property then computes its result on every read and can validate on every write.

JavaScript
const temp = { _celsius: 20 };

Object.defineProperty(temp, "fahrenheit", {
  get() {
    return this._celsius * 1.8 + 32;
  },
  set(value) {
    this._celsius = (value - 32) / 1.8;
  },
  enumerable: true,
});

console.log(temp.fahrenheit);
temp.fahrenheit = 212;
console.log(temp._celsius);
console.log(Object.getOwnPropertyDescriptor(temp, "fahrenheit"));
Text
68
100
{
  get: [Function: get],
  set: [Function: set],
  enumerable: true,
  configurable: false
}

Reading fahrenheit ran the getter, and the write ran the setter, which stored 100 in _celsius. The descriptor shows functions in place of value and writable. The output spans several lines because the printed form is longer than the line width Node.js uses.

Mixing the two forms is an error. A descriptor with get and value, or with get and writable, is rejected before anything changes.

JavaScript
try {
  Object.defineProperty({}, "bad", { get() { return 1; }, value: 2 });
} catch (err) {
  console.log(err.name);
}
Text
TypeError

Defining several properties and symbols

The key can be a symbol, which pairs well with non-enumerable attributes for internal metadata. For many properties at once, Object.defineProperties() takes a map of descriptors and returns the object.

JavaScript
const meta = Symbol("meta");
const item = {};

Object.defineProperties(item, {
  name: { value: "pen", enumerable: true },
  [meta]: { value: { internal: true } },
});

console.log(item);
console.log(item[meta]);
Text
{ name: 'pen' }
{ internal: true }

The symbol property is not enumerable, so the default print hides it, while reading it directly works. Without enumerable: false a symbol key would have appeared in the output as [Symbol(meta)]: ....

A mistake we hit: defining on an object that cannot grow

A new property cannot be added to an object that is frozen, sealed or marked non-extensible. The call throws, even in sloppy mode, because defineProperty() always reports failure with an exception.

JavaScript
const sealed = Object.preventExtensions({ a: 1 });

try {
  Object.defineProperty(sealed, "b", { value: 2 });
} catch (err) {
  console.log(err.name, err.message);
}

console.log("b" in sealed);
Text
TypeError Cannot define property b, object is not extensible
false

That is a difference from plain assignment, which fails silently in sloppy mode. We had a utility that attached a hidden id to incoming objects with defineProperty(), and it threw only when some caller handed it a frozen record. The fix was to check Object.isExtensible() first, or to wrap the id in a WeakMap keyed by the object, which needs no property at all.

Defining properties on classes and prototypes

The same call works on a class prototype, and that is how many libraries add members that must not show up in for...in loops. Methods you add to a prototype by plain assignment are enumerable, so they appear when someone iterates an instance with for...in. Defining them with enumerable: false, which is also the default, keeps them out of those loops, which is how built-in methods behave.

When you add an accessor to a prototype, remember that this inside the getter refers to the object the property was read on, not the prototype. That lets one definition serve every instance. If the getter needs per-instance state, store it on the instance under a separate key, or use a WeakMap keyed by the instance, and read it inside the getter.

Comparison with neighboring tools

GoalUseNote
One property with exact attributesObject.defineProperty()Unspecified attributes default to false on creation
Several properties with exact attributesObject.defineProperties()Same descriptors in one call
A normal propertyAssignmentAll attributes true
Lock every propertyObject.freeze()Sets all data properties to non-writable and non-configurable
Read the attributesObject.getOwnPropertyDescriptor()Returns the descriptor or undefined
Computed property in a literal or classget and set syntaxDefines enumerable, configurable accessors

For class-based code, a get accessor in the class body is clearer than defineProperty() on the instance, and it lives on the prototype so every instance shares it.

Where defineProperty stops being the right tool

It is the right tool when attributes matter: hiding a property from serialization, making a constant, or adding an accessor to an object you do not control. It is the wrong tool for ordinary properties, where it only adds noise and risks the defaults trap. It is also a poor fit for making data private. A non-enumerable property is still discoverable through Object.getOwnPropertyNames(), so for real privacy use a closure, a WeakMap or a #private class field.

Performance-sensitive code should be careful with defining properties one by one in hot paths. Objects created with a stable literal shape are easier for engines to optimize than objects that gain accessors afterward, so define the shape up front where you can.

The method is specified under Object.defineProperty, and MDN documents it on the Object.defineProperty page. To lock a whole object at once, read [the post on Object.freeze()](/library/javascript-object-freeze).

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.