This JavaScript exception can’t access the lexical declaration `variable’ before initialization occurs if a lexical variable has been accessed before initialization. This could happen inside any block statement when let or const declarations are accessed when they are undefined.
Message:
ReferenceError: Use before declaration (Edge) ReferenceError: can't access lexical declaration `variable' before initialization (Firefox) ReferenceError: 'variable' is not defined (Chrome)
Error Type:
ReferenceError
Cause of the error: Somewhere in the code, there is a lexical variable that was accessed before initialization.
Example 1: In this example, the const keyword is used with the variable inside the if statement, So the error has occurred.
function GFG() {
const var_1 = "This is" ;
if ( true ) {
const var_1 = var_1 + "GeeksforGeeks" ;
}
} function Geeks() {
try {
GFG();
console.log(
"'Can't access lexical declaration" +
"`variable'before initialization' " +
"error has not occurred" );
} catch (e) {
console.log(
"'Can't access lexical declaration" +
"`variable' before initialization'" +
" error has occurred" );
}
} Geeks() |
'Can't access lexical declaration`variable' before initialization' error has occurred
Example 2: In this example, the keyword is used with the variable, So the error has occurred.
function GFG() {
let var_1 = 3;
if ( true ) {
var_1 = var_1 + 5;
}
} function Geeks() {
try {
GFG();
console.log(
"'Can't access lexical declaration" +
"`variable' before initialization'" +
" error has not occurred" );
} catch (e) {
console.log(
"'Can't access lexical declaration" +
"`variable'before initialization'" +
" error has occurred" );
}
} Geeks() |
'Can't access lexical declaration`variable' before initialization' error has not occurred