Fix - Cannot access before initialization Error in JS

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

Fix - Cannot access before initialization #

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.

referenceerror cannot access before initialization

Here are some examples of how the error occurs.

index.js
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.

index.js
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); }
When a variable is declared using the 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.

referenceerror cannot access before initialization

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.

index.js
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.

index.js
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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee