Javascript Hoisting & TDZ

marzzy (Marzieh Moghtaderi)
2 min readMay 28, 2021
Javascript Hoisting

What’s hoisting?

Conceptually, hoisting happened when variables and function declarations are moved to the top of their scopes, like bubbles that come to the surface.

consider this example:

var a = 3;
let b = 4;
const c = 5;
d = 6;

function foo() {
// some codes
}

In the above example `a`, `b`, `c`, and `foo` are hoisted to the top of the code.
We didn’t explicitly write the `d`’s declaration, so when it comes to line 4, it’ll be declared and initialized at the same time, and no hoisting happened for `d`.
Keep in mind that, only the declarations are hoisted not initializations , therefore if we want to access the value of a hoisted item, before their actual written declaration, we shouldn’t expect it to return the initial value that we set for later in the code.

So what are their values then?

If either a variable that declares with `var` or a function declaration hoisted, the Javascript’s engine would declare and set the `undefined` value for it, till the running code gets to the written declaration and initialization value, watch this:

console.log(a); // undefined
console.log(b); // undefined

var a;
var b = 1;
console.log(a); // undefined
console.log(b); // 1

a = 2;
console.log(a) // 2

What about `let` and `const` variables?

When you define a variable with `let` or `const`, when it comes to the top of its scope, it hoists and goes to the TDZ.

TDZ (Temporal Dead Zone) is the time where the variable exists but is still uninitialized and cannot be accessed (so if we try to access it at this time, we will get an error). It ends when the code gets to the written declaration.
Even variables that declare with `var` have their TDZ time, but their TDZ is 0 for them, so it’s unobservable.

Whats happens under the hood?

But we should know that, in the real world it’s not what happened. Instead of move declarations, the Javascript’s engine simply put them into memory during the compile phase. So when the code starts to interpret from the beginning of each scope, it knows about the variables and functions that declare inside of it.

--

--