Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Object.defineProperty

Defines a property with exact settings: read-only, hidden, with a getter.

Available since: ES5

Syntax

Object.defineProperty(obj, key, descriptor)

Parameters

ParameterTypeDescription
objobjectThe object on which the property is defined.
keystring | symbolThe property name.
descriptorobjectThe property description: value, writable, enumerable, configurable, or get and set.

Return value

objectThe same object.

Examples

A read-only property:

const user = {};
Object.defineProperty(user, 'id', { value: 42, writable: false });
 
user.id = 7;
 
console.log(user.id);

Output:

42

A hidden property does not appear in Object.keys and JSON:

const user = { name: 'Anna' };
Object.defineProperty(user, 'password', { value: 'secret', enumerable: false });
 
console.log(Object.keys(user));
console.log(JSON.stringify(user));
console.log(user.password);

Output:

[
  "name"
]
{"name":"Anna"}
secret

Notes

By default every flag (writable, enumerable, configurable) is false for properties created this way. For ordinary properties created by assignment they are true.

See also

  • Object.freeze — Prevents any changes to an object.
  • get / set — Properties backed by functions: reading calls get, writing calls set.
  • Object.keys — Returns an array of an object's property names.

In the tutorial

  • Immutability — Mutable and immutable data in JavaScript: object references, copying with spread, the toSorted and with methods, Object.freeze and structuredClone.

Thanks for reading!

Donate to the site — we work hard for you.