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. 



HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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).

HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
    'use strict';
    Math.PI = 5;
</script>

chevron_right


Output(in console):

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

full-stack-img

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.