Skip to main content

Readonly properties

in JavaScript, a property can be made "read-only", so that it cannot be changed, deleted, or redefined.

There are several ways - from simple to maximally strict.


1. Via Object.defineProperty()

This is the main way to set a property with the desired attributes.

javascript
const user = {}; Object.defineProperty(user, 'name', { value: 'Tim', writable: false, // forbids changing it enumerable: true, // will be visible when iterated over configurable: false // cannot be deleted or redefined }); console.log(user.name); // "Tim" user.name = 'Oleh'; // will not change console.log(user.name); // "Tim" delete user.name; // will not be deleted console.log(user.name); // "Tim"

writable: false makes the property read-only. If you also set configurable: false, it cannot even be deleted.


What this looks like in the descriptor

javascript
console.log(Object.getOwnPropertyDescriptor(user, 'name'));

Prints:

javascript
{ value: 'Tim', writable: false, enumerable: true, configurable: false }

2. Via Object.freeze() (freeze the whole object)

If you want to make all properties immutable at once, you can "freeze" the object:

javascript
const user = { name: 'Tim', age: 25 }; Object.freeze(user); user.name = 'Oleh'; // will not change user.city = 'Kyiv'; // cannot add a new one delete user.age; // cannot delete console.log(user); // { name: 'Tim', age: 25 }

Object.freeze() does the following:

  • sets every existing property to writable: false and configurable: false;
  • forbids adding new ones.

3. Via a getter with no setter (computed, but read-only)

javascript
const user = { firstName: 'Tim', lastName: 'Smith', get fullName() { return `${this.firstName} ${this.lastName}`; } }; console.log(user.fullName); // "Tim Smith" user.fullName = 'Oleh Petrov'; // has no effect

If an object has a get but no set, that property automatically becomes read-only.


4. Via Object.seal() (partial protection)

If you don't want to "freeze" the object completely, but just forbid adding and removing properties:

javascript
const user = { name: 'Tim' }; Object.seal(user); user.name = 'Oleh'; // can be changed delete user.name; // cannot be deleted user.age = 30; // cannot be added

Unlike freeze(), seal() allows changing values, but forbids changing the object's structure.


SUMMARY

WayWhat it doesChange valuesAdd/remove
Object.defineProperty(obj, key, { writable: false })Makes one specific property read-onlyNoYes
Object.freeze(obj)Freezes the whole objectNoNo
Object.seal(obj)Forbids removing and adding propertiesYesNo
Getter with no setterA computed "read-only" propertyNoYes

In one phrase:

To make a property read-only, use

javascript
Object.defineProperty(obj, 'key', { value: val, writable: false });

or "freeze" the whole object with Object.freeze(obj).

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.