skip to Main Content

In this simple code, since the variable b is a let variable and i am trying to log() its value, I was expecting a reference error that said: cannot access ‘a’ before initialization,

but instead i am getting the error:
Uncaught ReferenceError: a is not defined

console.log(a);
let a=10;
var b=19;

a screenshot of the code and the error–>

i ran the same code in online js editors and they give the expected error, i am confused now :
the same code on an online editor with different error

2

Answers


  1. The reason you’re getting a Uncaught ReferenceError: a is not defined error instead of the expected cannot access ‘a’ before initialization is due to a difference in how let and var declarations are hoisted in JavaScript.

    When you use let to declare a variable, the variable is hoisted to the top of its block scope, but it is not initialized until the actual declaration statement is encountered in the code. That’s why you get a ReferenceError when you try to access the variable before its declaration.

    On the other hand, when you use var to declare a variable, it is hoisted to the top of its function or global scope, and it’s initialized with undefined at that point. Therefore, accessing a var variable before its declaration results in undefined rather than a ReferenceError.

    Login or Signup to reply.
  2. According to error docs it happens within any block statement

    Since you don’t have block statement, JS fires another error.

    enter image description here

    I suppose that in online editor, the code is executed by another code, so there could be block statement outside the "file".

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search