Last updated: Mar 2, 2024
Reading timeยท3 min
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.
const a = 'bobby'; // โ๏ธ TypeError: Assignment to constant variable. a = 'hadz';
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.
// ๐๏ธ using `let` let a = 'bobby'; a = 'hadz'; console.log(a); // ๐๏ธ "hadz"
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.
// ๐๏ธ using `var` var a = 'bobby'; a = 'hadz'; console.log(a); // ๐๏ธ hadz
Alternatively, you can declare a new variable using the const
keyword and use
a different name.
const a = 'bobby'; const b = a + ' hadz'; console.log(b); // ๐๏ธ "bobby hadz"
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.
const
variable with the same name in a different scopeYou can also declare a const
variable with the same name in a different scope,
e.g. in a function or an if
block.
const a = 'bobbyhadz.com'; if (true) { const a = 100; console.log(a); // ๐๏ธ 100 } function example() { const a = [1, 2, 3]; console.log(a); // ๐๏ธ [1, 2, 3] } example(); console.log(a); // ๐๏ธ hello
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.
const
keyword doesn't make objects immutableNote that the const
keyword prevents us from reassigning or redeclaring a
variable, but it doesn't make objects or arrays immutable.
const obj = { name: 'Bobby', }; // โ Works obj.name = 'Alice'; console.log(obj); // ๐๏ธ {name: 'Alice'} // โ๏ธ Error: Assignment to constant variable. obj = {name: 'Tom'};
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.
const arr = ['Bobby']; // โ Works arr[0] = 'Hadz'; console.log(arr); // ๐๏ธ ["Hadz"]
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.
You can learn more about the related topics by checking out the following tutorials: