Sunday, September 22, 2024
Google search engine
HomeLanguagesJavascriptJavaScript TypeError – “X” is read-only

JavaScript TypeError – “X” is read-only

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
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments