Borislav Hadzhiev
Tue Oct 19 2021·2 min read
Photo by Aliaksei
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.
Here is an example of how the error occurs.
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.
// 👇️ 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.
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.
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.
Note that the const
keyword prevents us from reassigning or redeclaring a
variable, but it doesn't make objects or arrays immutable.
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.
The behavior is the same when working with arrays.
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.
const
keyword prevents us from reassigning the variable, it doesn't make objects or arrays immutable.