In JavaScript, we have three ways to declare variables: var
, let
, and const
. While var
and let
are relatively straightforward, const
has some nuances that can catch developers off guard. Specifically, there is a difference between redeclaring a const
variable and redefining it, and the consequences can be surprising.
const
basics
First, let's review the basics of const
. When you declare a const
variable, it is bound to the value it is initialized with, and cannot be reassigned:
const myVar = 'Hello';
myVar = 'World'; // Uncaught TypeError: Assignment to constant variable.
Attempting to assign a new value to a const
variable in the same scope will result in a TypeError
. This behavior is intentional, as it helps to ensure that const
variables are truly constant within their scope.
redefining const
variables
However, redefining a const
variable in a different scope is allowed in JavaScript. For example:
const myVar = 'Hello';
if (true) {
const myVar = 'World'; // This is allowed
console.log(myVar); // 'World'
}
console.log(myVar); // 'Hello'
In this example, we define a const
variable myVar
with the value 'Hello'
. Then, within an if
block, we declare a new const
variable also named myVar
with the value 'World'
. This is allowed because the two variables are in different scopes. The inner myVar
variable effectively "shadows" the outer myVar
variable, and can be initialized with a different value.
When the code runs, the inner myVar
variable is in effect within the if
block, so console.log(myVar)
outputs 'World'
. Outside of the if
block, the outer myVar
variable is in effect, so console.log(myVar)
outputs 'Hello'
.
redeclaring const
variables
On the other hand, attempting to redeclare a const
variable in the same scope will result in a SyntaxError
. For example:
const myVar = 'Hello';
const myVar = 'World'; // Uncaught SyntaxError: Identifier 'myVar' has already been declared
This is because const
variables are block-scoped, like let
variables, so attempting to redeclare a const
variable in the same scope is like declaring a variable with the same name twice. This is not allowed in JavaScript.
conclusion
In conclusion, the difference between redefining and redeclaring const
variables in JavaScript can be subtle, but it's important to understand. Remember that redefining a const
variable by declaring a new variable with the same name in a different scope is allowed while redeclaring a const
variable in the same scope is not. By keeping this in mind, you can avoid some of the sneaky pitfalls of const
and write more reliable, bug-free code.
references
Follow me on Twitter for more such blogs.
Cheers ๐ป