Defining read-only properties in JavaScript

javascript override read-only property
javascript readonly property es6
cannot assign to because it is a read only property
cannot assign to read only property
javascript class read-only property
object.defineproperty prototype
object.defineproperty jest
javascript read-only error

Given an object obj, I would like to define a read-only property 'prop' and set its value to val. Is this the proper way to do that?

Object.defineProperty( obj, 'prop', {
    get: function () {
        return val;

The result should be (for val = 'test'):

obj.prop; // 'test'
obj.prop = 'changed';
obj.prop; // still 'test' since it's read-only

This method works btw: I'm just unsure if this is the easiest / smoothest / most proper way to do it...

You could instead use the writable property of the property descriptor, which prevents the need for a get accessor:

var obj = {};
Object.defineProperty(obj, "prop", {
    value: "test",
    writable: false

As mentioned in the comments, the writable option defaults to false so you can omit it in this case:

Object.defineProperty(obj, "prop", {
    value: "test"

This is ECMAScript 5 so won't work in older browsers.

Read-Only properties in JavaScript, Let's look at how we can make a JavaScript object property read-only using little-​known built in functions. JavaScript Object Literals are by  Given an object obj, I would like to define a read-only property 'prop' and set its value to val. Is this the proper way to do that? Object.defineProperty( obj, 'prop', { get: function () {

In new browsers or node.js it is possible to use Proxy to create read-only object.

var obj = {
    prop: 'test'

obj = new Proxy(obj ,{
    setProperty: function(target, key, value){
            return target[key];
        return target[key] = value;
    get: function(target, key){
        return target[key];
    set: function(target, key, value){
        return this.setProperty(target, key, value);
    defineProperty: function (target, key) {
        return this.setProperty(target, key, value);
    deleteProperty: function(target, key) {
        return false;

You can still assign new properties to that object, and they would be read-only as well.


// > 'test'

obj.prop = 'changed';
// > 'test'

// New value
obj.myValue = 'foo';
obj.myValue = 'bar';

// > 'foo'

TypeError: "x" is read-only, The JavaScript strict mode-only exception "is read-only" occurs when a global variable or object property that was assigned to is a read-only  By using the Object.defineProperty method you are able to define properties as 'read only' in JavaScript - this is done by setting the 'writable' property to 'true' while defining the property.

Because of the old browsers (backwards compatibility) I had to come up with accessor functions for properties. I made it part of bob.js:

var obj = { };
//declare read-only property.
bob.prop.namedProp(obj, 'name', 'Bob', true);
//declare read-write property.
bob.prop.namedProp(obj, 'age', 1);

//get values of properties.
console.log(bob.string.formatString('{0} is {1} years old.', obj.get_name(), obj.get_age()));
//set value of read-write property.
console.log(bob.string.formatString('Now {0} is {1} years old.', obj.get_name(), obj.get_age()));

//cannot set read-only property of obj. Next line would throw an error.
// obj.set_name('Rob');

// Bob is 1 years old.
// Now Bob is 2 years old.

I hope it helps.

Object.defineProperty(), I have a function constructor and I'm trying to declare some variables as read-​only properties, here's how it looks: function Stopwatch() { let  The property can still be deleted. If you make a property read-only using that method, you can still delete it using delete If you re-add that property after that, the newly added property will not be read-only. Sub properties are still modifiable. If your property points to an object, properties of that object are not read-only

Variable as a read-only property in object - JavaScript, One that I despise the most is the use of pseudo read-only properties in you can define a property that has a getter – allowing you to read  Pitfall: inherited read-only properties can’t be assigned to # If an inherited property is read-only, then we can’t use assignment to change it. The rationale is that overriding an inherited property by creating an own property can be seen as non-destructively changing the inherited property.

Defining Read Only Properties in JavaScript, They allow us to write code such that, when we access an attribute of an object, we are actually calling a function. We can use them to create read only properties​,  JavaScript Properties. Properties are the values associated with a JavaScript object. A JavaScript object is a collection of unordered properties. Properties can usually be changed, added, and deleted, but some are read only.

JavaScript: Read Only Attributes, In TypeScript 2.0, the readonly modifier was added to the language. Here's a simple Point type that declares two read-only properties, x and y : code has been compiled to JavaScript, all notions of readonly are gone. true if and only if this property shows up during enumeration of the properties on the corresponding object. Defaults to false. A data descriptor also has the following optional keys: value The value associated with the property. Can be any valid JavaScript value (number, object, function, etc). Defaults to undefined. writable

  • Possible duplicate:… (If you don't want to support older browsers, your method is the best)
  • I'm not sure if my code and your code produce the exact same result "on the outside", but your method is without doubt the more proper way to do it.
  • As per MDN documentation, Object.defineProperty(obj, "prop", {value:"test"}); is equivalent to the code above because writable is set to false by default.
  • Note that subProperties of an eventual object/array can still be modified. Only the "prop" key in this case cannot be reassigned.
  • WOW ! Proxies are so poweful! Thanks to make me discover such a great feature! Best answer!
  • Wait, .namedProp(obj, 'foo'), creates .get_foo(),/.set_foo() on the object itself? That's not very efficient. I think I'd go with a wrapper, e.g. X(obj).set('foo')/X(obj).get('foo').
  • For clarification: I think we are talking about two different things. You possibly want to keep the real object unchanged while having a wrapper around it; but I suggested to change the real object and have functions representing properties. Because for backwards compatibility, old-style JavaScript properties may be treated as fields. Thus, you would need to have accessors (functions) for it (plus I would suggest to remove traditional JS properties from the real object, thus have complete control over the properties). As about wrappers, that's also not bad, but differs from my approach.