Sometimes, we may run into the ‘TypeError: "x" is read-only’ when we’re developing JavaScript apps.
In this article, we’ll look at how to fix the ‘TypeError: "x" is read-only’ when we’re developing JavaScript apps.
Fix the ‘TypeError: "x" is read-only’ When Developing JavaScript Apps
To fix the ‘TypeError: "x" is read-only’ when we’re developing JavaScript apps, we should make sure that we aren’t trying to assign a value to a property that’s read-only.
On Edge, the error message for this error is TypeError: Assignment to read-only properties is not allowed in strict mode
.
On Firefox, the error message for this error is TypeError: "x" is read-only
.
And on Chrome, the error message for this error is TypeError: Cannot assign to read only property 'x' of #<Object>
for objects and TypeError: Cannot assign to read only property '0' of [object Array]
for arrays.
For instance, we shouldn’t write code like:
'use strict';
const obj = Object.freeze({name: 'Elsa', score: 157});
obj.score = 0;
'use strict';
Object.defineProperty(this, 'COUNT', {value: 2, writable: false});
COUNT = 3;
'use strict';
const frozenArray = Object.freeze([0, 1, 2]);
frozenArray[0]++;
In the first example, we called Object.freeze
on the object to make the object read-only, so we can’t assign new values to any top-level properties in it.
In the 2nd exanmple, we make COUNT
instance property read-only by setting writable
to `false, so we can’t assign a new value to it.
And in the 3rd example, we call Object.freeze
on the array to make it read-only, so we can’t change any value in it.
We’ll also get this error if we try to assign a value to read-only properties.
For instance, if we write:
'use strict';
Math.PI = 4;
then we’ll get this error.
To fix this, we write:
'use strict';
const obj = Object.freeze({name: 'Score', points: 157});
obj = {name: obj.name, points: 0};
'use strict';
let COUNT = 2;
COUNT = 3;
In the first example, we can replace the obj
variable with a new object to avoid this error.
And in the 2nd example, we can set COUNT
to a new value since we used let
to declare the variable.
Conclusion
To fix the ‘TypeError: "x" is read-only’ when we’re developing JavaScript apps, we should make sure that we aren’t trying to assign a value to a property that’s read-only.
On Edge, the error message for this error is TypeError: Assignment to read-only properties is not allowed in strict mode
.
On Firefox, the error message for this error is TypeError: "x" is read-only
.
And on Chrome, the error message for this error is TypeError: Cannot assign to read only property 'x' of #<Object>
for objects and TypeError: Cannot assign to read only property '0' of [object Array]
for arrays.