Solve - Assignment to Constant Variable in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

banner

Photo by Aliaksei

Solve - Assignment to Constant Variable #

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 can't be reassigned or redeclared.

assignment to constant variable

Here is an example of how the error occurs.

index.js
const a = 'hello'; // ⛔️ Assignment to constant variable. a = 'bye';

To solve the "Assignment to constant variable" error, declare the variable using the let keyword instead of using const. When a variable is declared using let, we can reassign its value as many times as necessary.

index.js
// 👇️ using `let` let a = 'hello'; a = 'bye'; console.log(a); // 👉️ "bye"

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

index.js
const a = 'hello'; const b = a + ' world'; console.log(b); // 👉️ "hello world"

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

index.js
const a = 'hello'; if (true) { const a = 100; console.log(a); // 👉️ 100 } function example() { const a = [1, 2, 3]; console.log(a); // 👉️ [1, 2, 3] } example();

The if statement and function have a different scope, so we are able to declare a variable with the same name in all 3 scopes. However, this prevents us from accessing the variable named a in the outer scope.

This can be confusing and is considered a bad practice, so it's best to avoid declaring variables of the same name in different scopes.

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

index.js
const obj = { name: 'James', }; // ✅ Works obj.name = 'John'; console.log(obj); // 👉️ {name: 'John'} // ⛔️ Error: Assignment to constant variable. obj = {name: 'Tom'};

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

We were able to directly change the value of the name property.

We can't reassign the variable to a new value, however we can change the values in the object directly.

The behavior is the same when working with arrays.

index.js
const arr = ['James']; // ✅ Works arr[0] = 'John'; console.log(arr); // 👉️ ["John"]

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

This is because the const keyword prevents us from reassigning the variable, it doesn't make objects or arrays immutable.
Use the search field on my Home Page to filter through my more than 1,000 articles.