Sukhjinder Arora
Sep 1, 2018 · 1 min read

As I have said before, if you try to access a let variable before it is declared, you will get a reference error. For example:

let x;
console.log(x); // You will get undefined not a reference error
x = 2;

In the above example, I am accessing the let variable after it is declared, so I am getting undefined instead of an error.

Before the code is executed, it is scanned for variable and function declarations. The var variables are set to undefined and let, const variable remain uninitialized.

A possible explanation for “ why we get reference error” could be that, when a let variable is accessed, the engine looks into its lexical environment. If the variable is uninitialized (does not have a value), the engine will throw a reference error. So that you won’t be able to use it before declaration.

If the engine still can’t find the value of the variable at the place it was declared (during execution), it will set the value to undefined.

You can read more about this on official ES6 docs section 13.3.1.

    Sukhjinder Arora

    Written by

    Web Developer. Tech Writer. Loves poetry, philosophy and programming. Find me @ https://sukhjinderarora.com/