Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

TypeError: invalid assignment to const "x"

The JavaScript exception "invalid assignment to const" occurs when it was attempted toalter a constant value. JavaScriptconstdeclarations can't be re-assigned or redeclared.

Message

TypeError: Assignment to constant variable. (V8-based)TypeError: invalid assignment to const 'x' (Firefox)TypeError: Attempted to assign to readonly property. (Safari)

Error type

What went wrong?

A constant is a value that cannot be altered by the program during normal execution. Itcannot change through re-assignment, and it can't be redeclared. In JavaScript,constants are declared using theconstkeyword.

Examples

Invalid redeclaration

Assigning a value to the same constant name in the same block-scope will throw.

js
const COLUMNS = 80;// …COLUMNS = 120; // TypeError: invalid assignment to const `COLUMNS'

Fixing the error

There are multiple options to fix this error. Check what was intended to be achievedwith the constant in question.

Rename

If you meant to declare another constant, pick another name and re-name. This constantname is already taken in this scope.

js
const COLUMNS = 80;const WIDE_COLUMNS = 120;

const, let or var?

Do not use const if you weren't meaning to declare a constant. Maybe you meant todeclare a block-scoped variable withlet orglobal variable withvar.

js
let columns = 80;// …columns = 120;

Scoping

Check if you are in the correct scope. Should this constant appear in this scope or wasit meant to appear in a function, for example?

js
const COLUMNS = 80;function setupBigScreenEnvironment() {  const COLUMNS = 120;}

const and immutability

Theconst declaration creates a read-only reference to a value. It doesnot mean the value it holds is immutable, just that the variableidentifier cannot be reassigned. For instance, in case the content is an object, thismeans the object itself can still be altered. This means that you can't mutate the valuestored in a variable:

js
const obj = { foo: "bar" };obj = { foo: "baz" }; // TypeError: invalid assignment to const `obj'

But you can mutate the properties in a variable:

js
obj.foo = "baz";obj; // { foo: "baz" }

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp