[Fixed] TypeError: Assignment to constant variable in JavaScript

Problem : TypeError: Assignment to constant variable

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.

Output

Solution : TypeError: Assignment to constant variable

Rename the variable

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

Change variable type to let or var

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

Change type to either let or var.

Output

Check if scope is correct

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 and immutability

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:

Output

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

Output

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

Was this post helpful?

Leave a Reply

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