Table of Contents
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.
1 2 3 4 5 6 7 |
const country1 = "India"; // attempt to reassign const variable country1= "china"; console.log(country1); |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 |
country= "china"; ^ TypeError: Assignment to constant variable. at Object.<anonymous> (HelloWorld.js:4:8) at Module._compile (internal/modules/cjs/loader.js:959:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10) at Module.load (internal/modules/cjs/loader.js:815:32) at Function.Module._load (internal/modules/cjs/loader.js:727:14) at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10) at internal/main/run_main_module.js:17:11 |
Solution : TypeError: Assignment to constant variable
Rename the variable
If you are supposed to declare another constant, just declare another name.
1 2 3 4 5 6 7 |
const country1 = "India"; const country2= "china"; console.log(country1); console.log(country2); |
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.
1 2 3 4 5 6 |
var country1 = "India"; country1= "China"; console.log(country1); |
Output
1 2 3 |
China |
Check if scope is correct
You can check if scope is correct as you can have different const in differnt scopes such as function.
1 2 3 4 5 6 7 |
const country1 = "India"; function countryName() { const country1= "China"; } |
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:
1 2 3 4 5 6 7 8 9 10 |
const country = { name : 'India' } country = { name : 'Bhutan' } console.log(country); |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 |
country = { ^ TypeError: Assignment to constant variable. at Object.<anonymous> (HelloWorld.js:5:9) at Module._compile (internal/modules/cjs/loader.js:959:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10) at Module.load (internal/modules/cjs/loader.js:815:32) at Function.Module._load (internal/modules/cjs/loader.js:727:14) at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10) at internal/main/run_main_module.js:17:11 |
But, you can change the content of country object as below:
1 2 3 4 5 6 7 8 |
const country = { name : 'India' } country.name = 'Bhutan' console.log(country); |
Output
1 2 3 |
{ name: 'Bhutan' } |
That’s all about how to fix TypeError: Assignment to constant variable in javascript.