Sometimes, we may run into the ‘ReferenceError: can’t access lexical declaration "X" before initialization’ when we’re developing JavaScript apps.
In this article, we’ll look at how to fix the ‘ReferenceError: can’t access lexical declaration "X" before initialization’ when we’re developing JavaScript apps.
Fix the ‘ReferenceError: can’t access lexical declaration "X" before initialization’ When Developing JavaScript Apps
To fix the ‘ReferenceError: can’t access lexical declaration "X" before initialization’ when we’re developing JavaScript apps, we should make sure that we don’t try to access variables declared with let
or const
before they’re defined.
The error message for the same error in Edge is ReferenceError: Use before declaration
.
And the error message for the same error in Chrome is ReferenceError: Use before declaration
.
For instance, if we have code like:
const bar = () => {
let foo = 33;
if (true) {
let foo = (foo + 55);
}
}
bar ();
We declared foo
inside and outside the if
block.
In the if
block, we would be trying to reference the foo
variable inside the block since we have let foo
inside the block.
However, on the right side, we’re trying to access it before the declaration is done.
Therefore, this error will be thrown.
To fix this, we should write:
const bar = () => {
let foo = 33;
if (true) {
foo = (foo + 55);
}
}
bar ();
This way, we reassign the value to the foo
variable that’s declared before the if
block is run.
And therefore, foo
is available for reassignment in the if
block.
Conclusion
To fix the ‘ReferenceError: can’t access lexical declaration "X" before initialization’ when we’re developing JavaScript apps, we should make sure that we don’t try to access variables declared with let
or const
before they’re defined.
The error message for the same error in Edge is ReferenceError: Use before declaration
.
And the error message for the same error in Chrome is ReferenceError: Use before declaration
.