TypeError: Assignment to Constant Variable in JavaScript

avatar

Last updated: Jul 25, 2022 Reading time · 3 min

banner

# TypeError: Assignment to Constant Variable in JavaScript

The "Assignment to constant variable" error occurs when trying to reassign or redeclare a variable declared using the const keyword.

When a variable is declared using const , it cannot be reassigned or redeclared.

assignment to constant variable

Here is an example of how the error occurs.

type error assignment to constant variable

# Declare the variable using let instead of const

To solve the "TypeError: Assignment to constant variable" error, declare the variable using the let keyword instead of using const .

Variables declared using the let keyword can be reassigned.

We used the let keyword to declare the variable in the example.

Variables declared using let can be reassigned, as opposed to variables declared using const .

You can also use the var keyword in a similar way. However, using var in newer projects is discouraged.

# Pick a different name for the variable

Alternatively, you can declare a new variable using the const keyword and use a different name.

pick different name for the variable

We declared a variable with a different name to resolve the issue.

The two variables no longer clash, so the "assignment to constant" variable error is no longer raised.

# Declaring a const variable with the same name in a different scope

You can also declare a const variable with the same name in a different scope, e.g. in a function or an if block.

declaring const variable with the same name in different scope

The if statement and the function have different scopes, so we can declare a variable with the same name in all 3 scopes.

However, this prevents us from accessing the variable from the outer scope.

# The const keyword doesn't make objects immutable

Note that the const keyword prevents us from reassigning or redeclaring a variable, but it doesn't make objects or arrays immutable.

const keyword does not make objects immutable

We declared an obj variable using the const keyword. The variable stores an object.

Notice that we are able to directly change the value of the name property even though the variable was declared using const .

The behavior is the same when working with arrays.

Even though we declared the arr variable using the const keyword, we are able to directly change the values of the array elements.

The const keyword prevents us from reassigning the variable, but it doesn't make objects and arrays immutable.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

  • SyntaxError: Unterminated string constant in JavaScript
  • TypeError (intermediate value)(...) is not a function in JS

book cover

Borislav Hadzhiev

Web Developer

buy me a coffee

Copyright © 2023 Borislav Hadzhiev

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • English (US)

The const declaration declares block-scoped local variables. The value of a constant can't be changed through reassignment using the assignment operator , but if a constant is an object , its properties can be added, updated, or removed.

The name of the variable to declare. Each must be a legal JavaScript identifier or a destructuring binding pattern .

Initial value of the variable. It can be any legal expression.

Description

The const declaration is very similar to let :

  • const declarations are scoped to blocks as well as functions.
  • const declarations can only be accessed after the place of declaration is reached (see temporal dead zone ). For this reason, const declarations are commonly regarded as non-hoisted .
  • const declarations do not create properties on globalThis when declared at the top level of a script.
  • const declarations cannot be redeclared by any other declaration in the same scope.

An initializer for a constant is required. You must specify its value in the same declaration. (This makes sense, given that it can't be changed later.)

The const declaration creates an immutable reference to a value. It does not mean the value it holds is immutable — just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g., its properties) can be altered. You should understand const declarations as "create a variable whose identity remains constant", not "whose value remains constant" — or, "create immutable bindings ", not "immutable values".

Many style guides (including MDN's ) recommend using const over let whenever a variable is not reassigned in its scope. This makes the intent clear that a variable's type (or value, in the case of a primitive) can never change. Others may prefer let for non-primitives that are mutated.

The list that follows the const keyword is called a binding list and is separated by commas, where the commas are not comma operators and the = signs are not assignment operators . Initializers of later variables can refer to earlier variables in the list.

Basic const usage

Constants can be declared with uppercase or lowercase, but a common convention is to use all-uppercase letters, especially for primitives because they are truly immutable.

Block scoping

It's important to note the nature of block scoping.

const in objects and arrays

const also works on objects and arrays. Attempting to overwrite the object throws an error "Assignment to constant variable".

However, object keys are not protected, so the following statement is executed without problem.

You would need to use Object.freeze() to make an object immutable.

The same applies to arrays. Assigning a new array to the variable throws an error "Assignment to constant variable".

Still, it's possible to push items into the array and thus mutate it.

Declaration with destructuring

The left-hand side of each = can also be a binding pattern. This allows creating multiple variables at once.

For more information, see Destructuring assignment .

Specifications

Browser compatibility.

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

  • Constants in the JavaScript Guide

How to Fix the ‘TypeError: invalid assignment to const “x” ‘ Error in Our JavaScript App?

  • Post author By John Au-Yeung
  • Post date August 22, 2021
  • No Comments on How to Fix the ‘TypeError: invalid assignment to const “x” ‘ Error in Our JavaScript App?

assignment to constant variable

Sometimes, we may run into the ‘TypeError: invalid assignment to const "x"’ when we’re developing JavaScript apps.

In this article, we’ll look at how to fix the ‘TypeError: invalid assignment to const "x"’ when we’re developing JavaScript apps.

Fix the ‘TypeError: invalid assignment to const "x"’ When Developing JavaScript Apps

To fix the ‘TypeError: invalid assignment to const "x"’ when we’re developing JavaScript apps, we should make sure we aren’t assigning a variable declared with const to a new value.

On Firefox, the error message for this error is TypeError: invalid assignment to const "x" .

On Chrome, the error message for this error is TypeError: Assignment to constant variable.

And on Edge, the error message for this error is TypeError: Assignment to const .

For example, the following code will throw this error:

We tried to assign 100 to COLUMNS which is declared with const , so we’ll get this error.

To fix this, we write:

to declare 2 variables, or we can use let to declare a variable that we can reassign a value to:

Related Posts

Sometimes, we may run into the 'RangeError: invalid date' when we're developing JavaScript apps. In…

Sometimes, we may run into the 'TypeError: More arguments needed' when we're developing JavaScript apps.…

Sometimes, we may run into the 'TypeError: "x" has no properties' when we're developing JavaScript…

assignment to constant variable

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

  • DSA with JS - Self Paced
  • JS A to Z Guide
  • JS Operator
  • JS Examples
  • Free JS Course

assignment to constant variable

  • Explore Our Geeks Community
  • JavaScript TypeError - "X" is read-only
  • JavaScript SyntaxError - Function statement requires a name
  • JavaScript SyntaxError - "x" is not a legal ECMA-262 octal constant
  • JavaScript URIError | Malformed URI Sequence
  • JavaScript SyntaxError - Return not in function
  • JavaScript ReferenceError Deprecated caller or arguments usage
  • JavaScript SyntaxError - Test for equality (==) mistyped as assignment (=)?
  • JavaScript TypeError - "X" is not a non-null object
  • JavaScript TypeError - "X" is not a function
  • JavaScript TypeError - "X" is not a constructor
  • JavaScript TypeError - "X" is (not) "Y"
  • JavaScript TypeError - "X" has no properties
  • JavaScript SyntaxError - Redeclaration of formal parameter "x"
  • JavaScript Error Object Complete Reference
  • JavaScript SyntaxError - Missing } after property list
  • JavaScript SyntaxError - Missing } after function body
  • JavaScript SyntaxError - Illegal character
  • JavaScript ReferenceError - variable is not defined
  • JavaScript SyntaxError - "0"-prefixed octal literals and octal escape sequences are deprecated

JavaScript TypeError – Invalid assignment to const “X”

This JavaScript exception invalid assignment to const occurs if a user tries to change a constant value. Const declarations in JavaScript can not be re-assigned or re-declared.

Error Type:

Cause of Error: A const value in JavaScript is changed by the program which can not be altered during normal execution. 

Example 1: In this example, the value of the variable(‘GFG’) is changed, So the error has occurred.

Output(in console):

Example 2: In this example, the value of the object(‘GFG_Obj’) is changed, So the error has occurred.

Please Login to comment...

Similar read thumbnail

  • JavaScript-Errors
  • Web Technologies

Please write us at contrib[email protected] to report any issue with the above content

Improve your Coding Skills with Practice

 alt=

Java2Blog

Java Tutorials

  • Java Interview questions
  • Java 8 Stream

Data structure and algorithm

  • Data structure in java
  • Data structure interview questions

Spring tutorials

  • Spring tutorial
  • Spring boot tutorial
  • Spring MVC tutorial
  • Spring interview questions
  • keyboard_arrow_left Previous

[Fixed] TypeError: Assignment to constant variable in JavaScript

Table of Contents

Problem : TypeError: Assignment to constant variable

Rename the variable, change variable type to let or var, check if scope is correct, const and immutability.

TypeError: Assignment to constant variable in JavaScript occurs when we try to reassign value to const variable. If we have declared variable with const , it can’t be reassigned.

Let’s see with the help of simple example.

Solution : TypeError: Assignment to constant variable

If you are supposed to declare another constant, just declare another name.

If you are supposed to change the variable value, then it shouldn’t be declared as constant.

Change type to either let or var.

You can check if scope is correct as you can have different const in differnt scopes such as function.

This is valid declaration as scope for country1 is different.

const declaration creates read only reference. It means that you can not reassign it. It does not mean that you can not change values in the object.

Let’s see with help of simple example:

But, you can change the content of country object as below:

That’s all about how to fix TypeError: Assignment to constant variable in javascript.

Was this post helpful?

Related posts:.

  • jQuery before() and insertBefore() example
  • jQuery append and append to example
  • Round to 2 decimal places in JavaScript
  • Convert Seconds to Hours Minutes Seconds in Javascript
  • [Solved] TypeError: toLowerCase is not a function in JavaScript
  • TypeError: toUpperCase is not a function in JavaScript
  • Remove First Character from String in JavaScript
  • Get Filename from Path in JavaScript
  • Write Array to CSV in JavaScript

Get String Between Two Characters in JavaScript

[Fixed] Syntaxerror: invalid shorthand property initializer in Javascript

Convert epoch time to Date in Javascript

assignment to constant variable

Follow Author

Related Posts

Get String between two characters in JavaScript

Table of ContentsUsing substring() MethodUsing slice() MethodUsing split() MethodUsing substr() Method 💡TL;DR Use the substring() method to get String between two characters in JavaScript. [crayon-6558827cb2ff0666877707/] [crayon-6558827cb2ff7339173953/] Here, we got String between , and ! in above example. Using substring() Method Use the substring() method to extract a substring that is between two specific characters from […]

assignment to constant variable

Return Boolean from Function in JavaScript

Table of ContentsUsing the Boolean() FunctionUse the Boolean() Function with Truthy/Falsy ValuesUsing Comparison OperatorUse ==/=== Operator to Get Boolean Using Booleans as ObjectsUse ==/=== Operator to Compare Two Boolean Objects Using the Boolean() Function To get a Boolean from a function in JavaScript: Create a function which returns a Boolean value. Use the Boolean() function […]

Create Array from 1 to 100 in JavaScript

Table of ContentsUse for LoopUse Array.from() with Array.keys()Use Array.from() with Array ConstructorUse Array.from() with length PropertyUse Array.from() with fill() MethodUse ... Operator Use for Loop To create the array from 1 to 100 in JavaScript: Use a for loop that will iterate over a variable whose value starts from 1 and ends at 100 while […]

Get Index of Max Value in Array in JavaScript

Table of ContentsUsing indexOf() with Math.max() MethodUsing for loopUsing reduce() FunctionUsing _.indexOf() with _.max() MethodUsing sort() with indexOf() Method Using indexOf() with Math.max() Method To get an index of the max value in a JavaScript array: Use the Math.max() function to find the maximum number from the given numbers. Here, we passed an array and […]

Update Key with New Value in JavaScript

Table of ContentsUsing Bracket NotationUpdate Single Key with New ValueUpdate Multiple Keys with New ValuesUsing Dot NotationUpdate Single Key with New ValueUpdate Multiple Keys with New ValuesUsing forEach() MethodUpdate All Keys with New ValuesUsing map() MethodUpdate All Keys with New Values Using Bracket Notation We can use bracket notation to update the key with the […]

Format Phone Number in JavaScript

Table of ContentsUsing match() MethodFormat Without Country CodeFormat with Country Code Using match() Method We use the match() method to format a phone number in JavaScript. Format Without Country Code To format the phone number without country code: Use the replace() method with a regular expression /\D/g to remove non-numeric elements from the phone number. […]

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

Let’s be Friends

© 2020-22 Java2Blog Privacy Policy

Itsourcecode.com

Typeerror assignment to constant variable

Doesn’t know how to solve the “Typeerror assignment to constant variable” error in Javascript?

Don’t worry because this article will help you to solve that problem

In this article, we will discuss the Typeerror assignment to constant variable , provide the possible causes of this error, and give solutions to resolve the error.

First, let us know what this error means.

What is Typeerror assignment to constant variable?

“Typeerror assignment to constant variable” is an error message that can occur in JavaScript code.

It means that you have tried to modify the value of a variable that has been declared as a constant.

In JavaScript, when you declare a variable using the const keyword, its value cannot be changed or reassigned.

Attempting to modify a constant variable, you will receive an error stating:

Here is an example code snippet that triggers the error:

In this example, we have declared a constant variable greeting and assigned it the value “Hello” .

When we try to reassign greeting to a different value (“Hi”) , we will get the error:

because we are trying to change the value of a constant variable.

Let us explore more about how this error occurs.

How does Typeerror assignment to constant variable occurs ?

This “ TypeError: Assignment to constant variable ” error occurs when you attempt to modify a variable that has been declared as a constant.

In JavaScript, constants are variables whose values cannot be changed once they have been assigned.

When you declare a variable using the const keyword, you are telling JavaScript that the value of the variable will remain constant throughout the program.

If you try to modify the value of a constant variable, you will get the error:

This error can occur in various situations, such as:

  • Attempting to reassign a constant variable:

When you declare a variable using the const keyword, its value cannot be changed.

If you try to reassign the value of a constant variable, you will get this error.

Here is an example :

In this example, we declared a constant variable age and assigned it the value 30 .

When we try to reassign age to a different value ( 35 ), we will get the error:

  • Attempting to modify a constant object:

If you declare an object using the const keyword, you can still modify the properties of the object.

However, you cannot reassign the entire object to a new value.

If you try to reassign a constant object, you will get the error.

For example:

In this example, we declared a constant object person with two properties ( name and age ).

We are able to modify the age property of the object without triggering an error.

However, when we try to reassign person to a new object, we will get the Typeerror.

  • Using strict mode:

In strict mode, JavaScript throws more errors to help you write better code.

If you try to modify a constant variable in strict mode, you will get the error.

In this example, we declared a constant variable name and assigned it the value John .

However, because we are using strict mode, any attempt to modify the value of name will trigger the error.

Now let’s fix this error.

Typeerror assignment to constant variable – Solutions

Here are the alternative solutions that you can use to fix “Typeerror assignment to constant variable” :

Solution 1: Declare the variable using the let or var keyword:

If you need to modify the value of a variable, you should declare it using the let or var keyword instead of const .

Just like the example below:

Solution 2: Use an object or array instead of a constant variable:

If you need to modify the properties of a variable, you can use an object or array instead of a constant variable.

Solution 3: Declare the variable outside of strict mode:

If you are using strict mode and need to modify a variable, you can declare the variable outside of strict mode:

Solution 4: Use the const keyword and use a different name :

This allows you to keep the original constant variable intact and create a new variable with a different value.

Solution 5: Declare a const variable with the same name in a different scope :

This allows you to create a new constant variable with the same name as the original constant variable.

But with a different value, without modifying the original constant variable.

For Example:

You can create a new constant variable with the same name, without modifying the original constant variable.

By declaring a constant variable with the same name in a different scope.

This can be useful when you need to use the same variable name in multiple scopes without causing conflicts or errors.

So those are the alternative solutions that you can use to fix the TypeError.

By following those solutions, you can fix the “Typeerror assignment to constant variable” error in your JavaScript code.

Here are the other fixed errors that you can visit, you might encounter them in the future.

  • typeerror unsupported operand type s for str and int
  • typeerror: object of type int64 is not json serializable
  • typeerror: bad operand type for unary -: str

In conclusion, in this article, we discussed   “Typeerror assignment to constant variable” , provided its causes and give solutions that resolve the error.

By following the given solution, surely you can fix the error quickly and proceed to your coding project again.

I hope this article helps you to solve your problem regarding a  Typeerror   stating  “assignment to constant variable” .

We’re happy to help you.

Happy coding! Have a Good day and God bless.

关于“TypeError: Assignment to constant variable”的问题解决方案

assignment to constant variable

在项目开发过程中,在使用变量声明时,如果不注意,可能会造成类型错误 比如:

Uncaught (in promise) TypeError: Assignment to constant variable. 未捕获的类型错误:赋值给常量变量。

我们使用 const 定义了变量且存在初始值。 后面又给这个变量赋值,所以报错了。

ES6 标准引入了新的关键字 const 来定义常量, const 与 let 都具有块级作用域:

  • 使用 const 定义的常量,不能修改它的值,且定义的常量必须赋初值;
  • let 定义的是变量,可以进行变量赋值操作,且不需要赋初值。

这个错误就是因为我们修改了常量而引起的错误,虽然某些浏览器不报错,但是无效果!

将 const 改为 let 进行声明。

assignment to constant variable

“相关推荐”对你有帮助么?

assignment to constant variable

请填写红包祝福语或标题

assignment to constant variable

你的鼓励将是我创作的最大动力

assignment to constant variable

您的余额不足,请更换扫码支付或 充值

assignment to constant variable

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。 2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

assignment to constant variable

IMAGES

  1. PPT

    assignment to constant variable

  2. PPT

    assignment to constant variable

  3. Equations, constants and variables

    assignment to constant variable

  4. PPT

    assignment to constant variable

  5. Constants, Variables, Expressions & Equations

    assignment to constant variable

  6. PPT

    assignment to constant variable

COMMENTS

  1. TypeError: Assignment to constant variable

    A user asks for help with a TypeError: Assignment to constant variable error in a Node.js project. The error occurs when trying to insert a file into a MySQL database using Express and MySQL. The error description and code snippets are provided by the user and the answer.

  2. TypeError: Assignment to Constant Variable in JavaScript

    The "Assignment to constant variable" error occurs when trying to reassign or redeclare a variable declared using the const keyword. When a variable is declared using const, it cannot be reassigned or redeclared. Here is an example of how the error occurs. index.js const a = 'bobby'; // ⛔️ TypeError: Assignment to constant variable. a = 'hadz';

  3. TypeError: invalid assignment to const "x"

    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 TypeError What went wrong? A constant is a value that cannot be altered by the program during normal execution.

  4. node.js

    Assignment to constant variable Ask Question Asked 4 years, 11 months ago Modified 3 years, 1 month ago Viewed 92k times 11 i try to read the user input and sent it as a email. but when i run this code it gives me this error: Assignment to constant variable. Any help will be appreciate

  5. const

    const declares block-scoped local variables that cannot be reassigned. Learn how to use const with initializers, destructuring, objects and arrays, and the temporal dead zone. See syntax, examples and browser compatibility of const.

  6. Assignment to constant variable exception

    1 Answer. Sorted by: 2. Use let instead of const. You can't reassign a variable which declared as const. If it is an object, you can change its properties. If it is an array, you can change its values, but still you can't reassign it. Share. Improve this answer.

  7. three.js

    Uncaught TypeError: Assignment to constant variable in javascript module Ask Question Asked 3 years, 4 months ago Modified 1 year, 8 months ago Viewed 2k times 2 I have declared a variable in one module like this: // first.js var folder; export {folder}; and I want to use it from a different module, like this:

  8. javascript

    I want to have a constant variable (globally) that can hold a node, however I don't know the value of that node yet! So I have to wait until a specific function is called to get the value that need to be assigned to my global constant. Below is my current code:

  9. JavaScript Error: Assignment to Constant Variable

    There are a few common causes for the "TypeError: Assignment to constant variable" error. Let's take a closer look at each one and discuss possible solutions. Cause 1: Attempting to Change a Constant Variable In JavaScript, const is used to declare variables that are meant to remain constant and cannot be reassigned.

  10. jQuery

    Uncaught TypeError: Assignment to constant variable. I know I'm writing about a very easy problem, but I can't figure out what the solution might be. HTML: <form id="target" class="signin-form" method="post"> <input type="text" placeholder="Username.."

  11. How to Fix Assignment to Constant Variable

    Solution 1: Use a Mutable Variable One possible solution to fix the Assignment to constant variable error is to use a mutable variable instead of a constant. By declaring the variable using the let or var keyword, you allow the value to be reassigned as needed. 1 let pi = 3.14159; 2 pi = 3.14; // This will not produce an error

  12. TypeError: Assignment to constant variable. React.js Hook

    1 You probably meant to use arrow => instead of an assignment operator: setToggle (toggle = !toggle) ----> setToggle (toggle => !toggle) - Yousaf Nov 6, 2020 at 17:59 Add a comment 2 Answers Sorted by: 1 The error is self descriptive I guess. You need to use the setter instead of assigning a value directly to your state object.

  13. How to Fix Uncaught TypeError: Assignment to constant variable

    Uncaught TypeError: Assignment to constant variableIf you're a JavaScript developer, you've probably seen this error more than you care to admit. This one oc...

  14. How to Fix the 'TypeError: invalid assignment to const "x" ' Error in

    to declare 2 variables, or we can use let to declare a variable that we can reassign a value to: let COLUMNS = 80; // ... COLUMNS = 100; Conclusion. To fix the 'TypeError: invalid assignment to const "x"' when we're developing JavaScript apps, we should make sure we aren't assigning a variable declared with const to a new value.

  15. JavaScript TypeError

    This JavaScript exception invalid assignment to const occurs if a user tries to change a constant value. Const declarations in JavaScript can not be re-assigned or re-declared. ... invalid assignment to const "x" (Firefox) TypeError: Assignment to constant variable. (Chrome) TypeError: Assignment to const (Edge) TypeError: Redeclaration of ...

  16. [Fixed] TypeError: Assignment to constant variable in JavaScript

    TypeError: Assignment to constant variable in JavaScript occurs when we try to reassign value to const variable. If we have declared variable with const, it can't be reassigned. Let's see with the help of simple example. Typeerror:assignment to constant variable 1 2 3 4 5 6 7 const country1 = "India"; // attempt to reassign const variable

  17. Typeerror assignment to constant variable [SOLVED]

    "Typeerror assignment to constant variable" is an error message that can occur in JavaScript code. It means that you have tried to modify the value of a variable that has been declared as a constant. In JavaScript, when you declare a variable using the const keyword, its value cannot be changed or reassigned.

  18. How to assign a value to a constant variable which belongs to a

    5. You cannot assign anything to a constant object. A constant object can only be initialized at the point of declaration, as in. struct temp t = { 5 }; I.e. you get only one chance. If you missed your chance to initialize a constant object, you are out of luck - the object will remain uninitialized forever. For this reason it is generally not ...

  19. php

    3. No, what the OP wants to do is entirely valid. Assigning a variable's value to a constant makes complete sense, in fact it's one of the fundamental ways to use it. You want to freeze the value you just retrieved from elsewhere, in your code, keeping it from being modified accidentally later. - Kaz Vorpal.

  20. C# Assign Variable to Constant

    I am trying to assign a variable to a constant. Yes I understand the fact and the theory that a constant should not be assigned a variable but here is the scenario... I have created an assembly and I need to do version checking on the assembly as it could be plugged into various applications. I am writing and reading from XML files, and the ...

  21. 关于"TypeError: Assignment to constant variable"的问题解决方案

    本文介绍了在 JavaScript 中使用 const 定义的变量时,如何避免出现类型错误的问题,以及如何使用 const 的初始化方式。文章还提供了一些示例代码和链接,帮助读者理解和掌握 const 的用法。