The open blogging platform. Say no to algorithms and paywalls.

How to Fix the “Cannot access before initialization” Reference Error in JavaScript

The "cannot access before initialization" reference error occurs in JavaScript when you try to access a variable before it is declared with let or const and initialized in the same scope. To fix it, initialize the variables before accessing them.

image

Here are some examples of the error occurring:

// ❌ ReferenceError: Cannot access 'num' before initialization
console.log(num);
let num = 2;

// ❌ ReferenceError: Cannot access 'name' before initialization
console.log(name);
const name = "Coding Beauty";

// ❌ ReferenceError: Cannot access 'arr' before initialization
arr = [7, 8, 9];
let arr = [3, 4, 5];

To solve the error, you need to initialize the variable before accessing it.

// ✅ No error
let num = 2;
console.log(num); // 2

// ✅ No error
const name = "Coding Beauty";
console.log(name); // Coding Beauty

// ✅ No error
let arr = [3, 4, 5];
arr = [7, 8, 9];

var vs let

The occurrence of this error shows an important difference between the var and let keywords. If you had declared the variable with var, the error wouldn't have occurred.

// No error

console.log(num); // undefined
var num = 2;

// No error
console.log(name); // undefined
var name = "Coding Beauty";
// No error
arr = [7, 8, 9];
var arr = [3, 4, 5];

This happens because variables declared with the var keyword are hoisted - they are moved by the JavaScript interpreter to the top of the current scope (to the top of the current script or current function).

Basically, this is what happens to our variables declared with var:

var num;
var name;
var arr;

console.log(num); // undefined
num = 2;

console.log(name); // undefined
name = "Coding Beauty";

arr = [7, 8, 9];
arr = [3, 4, 5];

Note: The declarations are hoisted, but the initializations are not.

Because of this hoisting, even when the variable is declared in a non-function block, like an if block, the error will still not occur if you try to access the variable from outside the if statement.

// No error!

console.log(num); // undefined

if (true) {
  var num = 2;
}

Only the global scope and function scopes are used for hoisting, so like before, the variable declaration is moved to the top of the file.

var num;

console.log(num); // undefined

if (true) {
  num = 2;
}



Continue Learning