Sukhjinder Arora
Sep 1, 2018 · 1 min read

I think you are mistaken about how hoisting happen in JavaScript. The variables are not physically moved in your code during hoisting. So your code:

console.log(x);
let x = 2;

Wouldn’t transform into this code:

let x;
console.log(x);
x = 2;

Just microseconds before your code is run, a memory space is created and your code is scanned for variable and function declaration. After that a mapping between identifier and value(or function object) is stored in that memory space called lexical environment. It is, what we call hoisting (in simple terms). It is in this step, var variable are set to undefined and let, const remain uninitialized. After this your code is actually executed.

Note — Your actual source code will not be changed.

So the engine will first encounter console.log statement before variable x declaration and it would not be able to find the value of x. So it will throw an error.

I hope that makes it clear.

Please watch this video for further clarification.

    Sukhjinder Arora

    Written by

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