Borislav Hadzhiev
Tue Oct 19 2021·2 min read
Photo by Artur Kornakov
The "Cannot access before initialization" error occurs when a variable
declared using let
or const
is accessed before it was initialized in the
scope. To solve the error, make sure to initialize the variable before accessing
it.
Here are some examples of how the error occurs.
arr = [3, 2, 1]; // ⛔️ Cannot access 'arr' before initialization let arr = [1, 2, 3]; if (5 === 5) { console.log(num); // ⛔️ Cannot access 'num' before initialization const num = 100; } function example() { console.log(str); // ⛔️ Cannot access 'str' before initialization let str = 'hello'; }
To solve the error, we have to initialize the variables before using them.
let arr = [1, 2, 3]; arr = [3, 2, 1]; if (5 === 5) { const num = 100; console.log(num); } function example() { let str = 'hello'; console.log(str); }
let
and const
keywords, it is only available in the scope in which it is defined.If you're unable to track down where exactly the error occurs in your code, look at the error message in your browser's console or your Node.js terminal.
The screenshot above shows that the error was thrown on line 4
in the
index.js
file.
If a variable is declared using the var
keyword the declaration gets hoisted
to the top. However, this is not the case when using the let
and const
keywords.
console.log(arr); // 👉️ undefined var arr = [1, 2, 3];
Had we used let
or const
, we would have gotten the "Cannot access before
initialization" error.
How hoisting works with variables declared using var
is it lifts the variable
declaration to the top of the file.
Behind the scenes, this is what happens.
var arr; console.log(arr); // 👉️ undefined arr = [1, 2, 3];
However, this is not the behavior when using the let
and const
keywords to
declare a variable.
When using let
and const
always make sure to initialize the variables before
accessing them.