Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

TypeError: "x" is read-only

The JavaScriptstrict mode-only exception"is read-only" occurs when a global variable or objectproperty that was assigned to is a read-only property.

Message

TypeError: Cannot assign to read only property 'x' of #<Object> (V8-based)TypeError: "x" is read-only (Firefox)TypeError: Attempted to assign to readonly property. (Safari)

Error type

What went wrong?

The global variable or object property that was assigned to is a read-only property.(Technically, it is anon-writable data property.)

This error happens only instrict mode code. Innon-strict code, the assignment is silently ignored.

Examples

Invalid cases

Read-only properties are not super common, but they can be created usingObject.defineProperty() orObject.freeze().

js
"use strict";const obj = Object.freeze({ name: "Elsa", score: 157 });obj.score = 0; // TypeError("use strict");Object.defineProperty(this, "LUNG_COUNT", { value: 2, writable: false });LUNG_COUNT = 3; // TypeError("use strict");const frozenArray = Object.freeze([0, 1, 2]);frozenArray[0]++; // TypeError

There are also a few read-only properties built into JavaScript. Maybe you tried toredefine a mathematical constant.

js
"use strict";Math.PI = 4; // TypeError

Sorry, you can't do that.

The global variableundefined is also read-only, so you can't silence theinfamous "undefined is not a function" error by doing this:

js
"use strict";undefined = function () {}; // TypeError: "undefined" is read-only

Valid cases

js
"use strict";let obj = Object.freeze({ name: "Score", points: 157 });obj = { name: obj.name, points: 0 }; // replacing it with a new object works

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp