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.
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
console.log(Object.getOwnPropertyDescriptor(user, 'name'));Prints:
{
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:
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: falseandconfigurable: false; - forbids adding new ones.
3. Via a getter with no setter (computed, but read-only)
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 effectIf 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:
const user = { name: 'Tim' };
Object.seal(user);
user.name = 'Oleh'; // can be changed
delete user.name; // cannot be deleted
user.age = 30; // cannot be addedUnlike freeze(), seal() allows changing values,
but forbids changing the object's structure.
SUMMARY
| Way | What it does | Change values | Add/remove |
|---|---|---|---|
Object.defineProperty(obj, key, { writable: false }) | Makes one specific property read-only | No | Yes |
Object.freeze(obj) | Freezes the whole object | No | No |
Object.seal(obj) | Forbids removing and adding properties | Yes | No |
| Getter with no setter | A computed "read-only" property | No | Yes |
In one phrase:
To make a property read-only, use
javascriptObject.defineProperty(obj, 'key', { value: val, writable: false });or "freeze" the whole object with
Object.freeze(obj).
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.