Open In App

JavaScript TypeError – “X” is read-only

Improve
Improve
Like Article
Like
Save
Share
Report

This JavaScript exception is read-only works in strict mode-only and It occurs if a global variable or object property which has assigned to a value, is a read-only property.

Message:

TypeError: Assignment to read-only properties is not allowed in strict mode (Edge)
TypeError: "x" is read-only (Firefox)
TypeError: 0 is read-only (Firefox)
TypeError: Cannot assign to read only property 'x' of #<Object> (Chrome)
TypeError: Cannot assign to read only property '0' of [object Array] (Chrome)

Error Type:

TypeError

Cause of Error: The global variable or object property that has assigned value is a read-only property. You can not write data in those variables.

Example 1: In this example, any property of GFG_Obj can not be modified. 

Javascript




'use strict';
let GFG_Obj = Object.freeze({ prop1: 'val1', prop2: 'val2' });
GFG_Obj.prop2 = 0;  // TypeError


Output(in console):

TypeError: Assignment to read-only properties is not allowed in strict mode

Example 2: In this example, the value of Math.PI can not be changed(Which is read-only).

Javascript




'use strict';
Math.PI = 5;


Output(in console):

TypeError: Assignment to read-only properties is not allowed in strict mode

Last Updated : 22 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads